$(function(){
	        
            selectSuppGoodsLastStyle();

            // 增加门票人数
            $('.orderBox').on('click','.orderAdd',function(){
                LVMAMA.order.ticket.bookNumOnchangeComm(this,"+");
            });

            // 减少门票人数
            $('.orderBox').on('click','.orderReduce',function(){
                LVMAMA.order.ticket.bookNumOnchangeComm(this,"-");
            });

            //添加更多商品
            $(".js_add_ticket").bind('click',function(){
                LVMAMA.order.ticket.clickOtherMoreGoods();
            });

            //选中商品
            $('#otherTicketDiv').on('click','.js_select_goods',function(){
                LVMAMA.order.ticket.clickChoiceGoods($(this));
            });

            //确定选中商品
            $('#otherTicketDiv').on('click','.js_ticketConfirm',function(){
                LVMAMA.order.ticket.clickSelectGoods();
                if(LVMAMA.order.ticket.isSelectAllGoods()){
                    $('.js_add_ticket').hide();
                }else{
                    $('.js_add_ticket').show();
                }
            });
            //删除选中的商品
            $(".orderBox:first").on('click','.ticketDelBtn',function(){
                LVMAMA.order.ticket.clickDeleteGoods($(this));
                $('.js_add_ticket').show();
            });

            // 保险数量变化
            /*$('#order_submit').on('change','#insuranceDiv .num_text',function(){
                LVMAMA.order.ticket.insuranceNumChange(this,"");
            });*/

			/*$("ul.bx_tab li").live('click', function(){
				LVMAMA.order.ticket.setInsuranceNum(LVMAMA.order.ticket.calBaseTicketPersonCount());
                LVMAMA.order.ticket.bxNumBussiness();
				bookNumOnchangeCallback.invoke();
			});*/

            //切换保险 update by luo
            $("ul.js_bxtab li").live('click', function(){
            	var isEqualProduct=false;
                var isSameInsurance=false;
            	var newProductType=$(this).attr("productType");
            	var newSuppgoodsId=$(this).attr("data-id");
            	$("ul.js_bxtab li.active").each(function(){
            		var oldProductType=$(this).attr("productType");
            		var suppgoodsId=$(this).attr("data-id");
            		if(oldProductType==newProductType||suppgoodsId==undefined){
            			isEqualProduct=true;
                        if(suppgoodsId==newSuppgoodsId){
                            isSameInsurance=true;
                        }
            			return;
            		}
            	});
                if(isSameInsurance&&newSuppgoodsId!=undefined){
                    $(this).removeClass('active');
                    $(this).parent().find(":first").addClass('active');
                }else{
                    if(isEqualProduct||newSuppgoodsId==undefined){
                        $(this).addClass('active').siblings().removeClass('active');
                    }else{
                        $(this).addClass('active');
                    }
                }
            	//添加判断是否包含保险代码
            	//if($('input[name="invoiceInfo.invoiceType"]:checked').val()==1){
           			//电子发票
            	   var bxGoodsIdList=[];
	               $("ul.js_bxtab li.active").each(function(){
	               		var bxGoodsId=$(this).attr("data-id");
	               		if(bxGoodsId != undefined){
	               		   bxGoodsIdList.push(bxGoodsId);
	               		}
	               });
                   if(bxGoodsIdList.length>0){
                   		$("input[name='insIncluded']").val("N");
                   		$('#invoice_insurance').show();
                   		if($('#invoice_insurance_check').attr("checked")){
                   			$("input[name='insIncluded']").val("Y");
                   			//包含保险且勾选
               				$('#invoiceAddressBox').show();
               				var firstAddressLi = $('.invoice_address_list li.active');
                            //最后一个除外
                            if (firstAddressLi.size() == 1 && !firstAddressLi.hasClass('address_add')) {
                                var add_address_name =firstAddressLi.children('.receiverName').text();
                                $('#invoiceFullName').val(add_address_name);

                                var add_address_mobile =firstAddressLi.children('.mobileNumber').text();
                                $('#invoiceMobile').val(add_address_mobile);
                            
                                var add_address_province= firstAddressLi.children('.province').text();
                                $('#invoiceProvince').val(add_address_province);
                           
                                var add_address_city= firstAddressLi.children('.city').text();
                                $('#invoiceCity').val(add_address_city);
                                      
                                var add_address_detail= firstAddressLi.children('.address').text();
                                $('#invoiceStreet').val(add_address_detail);
                                  
                                var add_address_zipcode= firstAddressLi.children('.postCode').text();
                                $('#invoicePostalCode').val(add_address_zipcode);
                            }
                   		}else{
                   			$('#invoiceAddressBox').hide();
                   		}
                   	}else{
                   		$('#invoice_insurance').hide();
                   		$('#invoiceAddressBox').hide();
                   	}
           		//}
                LVMAMA.order.ticket.bxNumBussiness();
                bxOnchangeCallback.invoke();
            });


			//增加游玩人手机号-注册功能
			$("body").delegate("[item_type='main']", "blur", function(){
				var jThis = $(this);
				var mobileVal = jThis.val();
				if( !_lvPageTool.isMobile(mobileVal) ){	//condition: 非法手机号码
                    lv_validation.errorHtml(jThis,'手机号码不正确。');
					return;
				}
				else{
                    lv_validation.okHtml(jThis);
				}
				if(_lvPageTool.isLogin()){				//condition: 已经登录
					return;
				}

				_lvPageTool.isFrozenMobile({
					mobileVal: mobileVal,
					frozenFun: function(){lv_validation.errorHtml(jThis,'此手机号已被驴妈妈冻结，不能下单，请更换手机号下单。');},
					isLvmmFun: function(){
                        lv_validation.okHtml(jThis);
					}});
			});
			//增加收件人手机注册功能
			//该功能是对游玩人手机号注册功能的补充，对于游玩人无手机号的情况拿收件人手机号进行注册，并校验是否冻结
			$("body").delegate("[item_type='main_deliv']", "blur", function(){
				//如果游玩人手机号已经存在也不进行后续操作。
                //如果要输入手机验证码，则必须要填写手机号 2018年6月15日10:09:30
				if($("body [item_type='main']").length>0){
					return;
				}

				var jThis = $(this);
				var mobileVal = jThis.val();
                if( !_lvPageTool.isMobile(mobileVal) ){	//condition: 非法手机号码
                    lv_validation.errorHtml(jThis,'手机号码不正确');
                    return;
                }
                else{
                    lv_validation.okHtml(jThis);
                }
                if(_lvPageTool.isLogin()){				//condition: 已经登录
                    return;
                }
                _lvPageTool.isFrozenMobile({
                    mobileVal: mobileVal,
                    frozenFun: function(){lv_validation.errorHtml(jThis,'此手机号已被驴妈妈冻结，不能下单，请更换手机号下单。');},
                    isLvmmFun: function(){
                        lv_validation.okHtml(jThis);
                    }});
			});
			
			$(".orderNumBox input").live("change",function(){
				var max=$(this).attr("maxQuantity");
				var min=$(this).attr("minQuantity");
				var mainItem=$(this).siblings("input[type=text]").attr("mainItem");
				var num=$(this).val();

                var goodsid = $(this).attr('goodsid');
                var ticketType = $(this).attr("ticketType");
                if(ticketType == "DISNEY_TICKET"){
                    var msg = LVMAMA.order.ticket.checkTotalNumDisneyTicket(num);
                    if(msg != ""){
                        num = LVMAMA.order.ticket.countDisneyTicketNum(num,goodsid);
                        alert(msg);
                        $(this).val(num);
                    }
                }

				var integerReg = "^[1-9]*[0-9][0-9]*$";
				if($.trim($(this).val()).match(integerReg)){
					if(parseInt(num)>parseInt(max)){
						$(this).val(max);
					}
					if(parseInt(num)<parseInt(min)){
						$(this).val(min);
					}
				}else{
					if(mainItem=="true"){
						if(min>0){
							$(this).val(min);
						}else{
							$(this).val(1);
						}
					}else{
						$(this).val(0);
					}
				}
				if(parseInt(num)>=parseInt(max)){
					$(this).siblings('a.orderAdd').addClass('num_stop'); 
					LVMAMA.order.ticket.showInfo($(this),"最多预订数量："+max);
				}else{
					$(this).siblings('a.orderAdd').removeClass('num_stop');
				}
				if(parseInt(num)<=parseInt(min)&&mainItem=="true"){
					LVMAMA.order.ticket.showInfo($(this),"至少预订数量："+min);
				}
				
				if(parseInt(num)<=parseInt(min)){
					$(this).siblings('a.orderReduce').addClass('num_stop'); 
				}else{
					$(this).siblings('a.orderReduce').removeClass('num_stop');
				}
				
				LVMAMA.order.ticket.bxNumBussiness();
				bookNumOnchangeCallback.invoke();
			});
			
			// 提交订单
            $('div.payBox a.js_tijiao').bind('click',function(){
                if(!$(".payBox-contract").find(".check").hasClass("checked")){
                    alert("请同意驴妈妈旅游网预订条款。");
                    return;
                }
                doSubmitFlag = true;
                if(!isDisneyShowFlag()){
                    submitOrder();
                }
			});

        //赋值用户填写信息到userInfos中
        $("#Jtenantlist").live('mouseout',function(){
            LVMAMA.order.ticket.fillUserInfosMap();
        });
        $("#expressageInfoDiv").live('mouseout',function(){
            LVMAMA.order.ticket.fillUserInfosMap();
        });


    //获取打码手机号
    $.getJSON("https://login.lvmama.com/nsso/ajax/getUserHiddenMobile.do?jsoncallback=?", function (json) {
        if (json.success == true) {
            var _result = json.result;
            $("#riskAuthCodeInfo").html('<i class="tip-icon tip-icon-info"></i>已绑定手机号 ' + _result);
            $("#riskAuthCodeInfo").show();
        }
    });

    //发送验证码倒计时
    var times = 60, timer4 = null, downTime = true;
    $('.js_order_yzm').live('click', function () {
        if (times == 60 && downTime) {
            downTime = false;
            var This = $(this);
            This.html('<span class="c_f60">60</span>秒后重发').addClass('disabled');

            timer4 = setInterval(function () {
                times--;
                This.find('span').html(times);
                if (times == 0) {
                    clearTimeout(timer4);
                    This.html('重发验证码').removeClass('disabled');
                    times = 60;
                    downTime = true;
                }
            }, 1000);

            //发送验证码
            $.getJSON("https://login.lvmama.com/nsso/ajax/sendRiskAuthenticationCode.do?jsoncallback=?", function (json) {
            	if (json.success == false) {
                	var errorTips = "短信发送失败,请联系客服! (错误:"+json.errorText+")";
                	if (json.errorText == 'phoneWarning') {
                	    errorTips = '已超过每日发送上限，请于次日再试';
                	} else if (json.errorText == 'ipLimit') {
                	    errorTips = '当前IP发送频率过快，请稍后重试';
                	} else if (json.errorText == 'waiting') {
                	    errorTips = '发送频率过快，请稍后重试';
                	}
                	alert(errorTips);
                }
            });
        }
    });

});

var ticketOrderSubmitFlag=false;
var doSubmitFlag=false;
var maxBonus=0;
function bonusChange(){
	$("#target").val("bonus");
	if(ValidateBonus()){
		checkStock(true);
	}
}

function validateCircusBeforeSubmit(){
    //长隆马戏场地选择验证
    var $circus = $('#circus');
    var $d_ccSelect = $('.js_select_circus');
    if($circus.length != 0) {
        if ($d_ccSelect.prev(".selectbox").css("display")=="none") {
            $('body,html').scrollTop(0);
            alert('暂无场次信息，请选择其他日期。');
            return false;
        }
        if ($d_ccSelect.val() == "-请选择场次-") {
            $('body,html').scrollTop(0);
            alert('请选择游玩场次。');
            //$circus.find('.d_floatTip').show();
            return false;
        }
    }
    return true;
}

//提交订单
function submitOrder(){
    //去掉错误提示
    LVMAMA.order.ticket.showErrorInfo(false);
	var suppGoodsIdList=[];
    $(".ticketLi:visible .js_input").each(function () {
        suppGoodsIdList.push($(this).attr("goodsId"));
     });
    if($("input[name='limitChild']").val() =="Y"&&suppGoodsIdList.length==1){
            $.alert("很遗憾，受限于景区要求，儿童需同行成人陪伴，无法单独预订儿童票！");
            return;
     }
    var skuRelation = $("[name='masterSlaveGoodsRelation']").attr("value");
    skuRelation = eval("("+skuRelation+")");
    for(var key in skuRelation){
        if(parseInt($("[goodsid='"+key+"']").attr("value")) > 0 && parseInt($("[goodsid='"+skuRelation[key]+"']").attr("value")) == 0){
            alert("很遗憾，受限于景区要求，儿童需同行成人陪伴，无法单独预订儿童票");
            return;
        }
    }
    if(ticketOrderSubmitFlag){
        return;
    }
    //验证票种信息
    if(!checkTicketTypeInfor()){
        return;
    }
    
    if(!checkSplitTicketDate()){
    	return;
    }
    
    if(!NewExpress.check()){
        return;
    }
    if($("#isFrozenFlag").val()=='Y'){
        return;
    }

    if(!validateCircusBeforeSubmit()){
        return;
    }

    if(lv_validation.allok() && LVMAMA.order.ticket.orderValidate()){
    	if(!checkDisplayNoneElement()){
    		return;
    	}
    	
        //是否是马戏票
        if(isCircusFlag()){
            $(".ticketLi:visible .js_input").each(function(){
                var goodsId=$(this).attr("goodsId");
                var mainItem=$(this).attr("mainItem");
                if(mainItem=="true"){
                    var option = $('.js_select_circus option:selected');
                    $("input[name='itemMap["+goodsId+"].circusActInfo.circusActId']").val(option.attr("data-id"));
                    $("input[name='itemMap["+goodsId+"].circusActInfo.circusActStartTime").val(option.attr("start-time"));
                    $("input[name='itemMap["+goodsId+"].circusActInfo.circusActEndTime").val(option.attr("end-time"));
                }
            });
        }
        //是否使用优惠券
        //var couponChecked= $("#couponChecked").val();
        var youhuiType = $("#youhui:checked").val();
        if(youhuiType=="coupon"&&$.trim($("#couponCode").val())==""){
            $("#couponVerifySpan").closest("div").addClass("error_show");
            $("#couponVerifySpan").next("span.error_text").html('<i class="tip-icon tip-icon-error"></i>请输入优惠券代码.');
            return false;
        }
        if(youhuiType=="bonus"){
            if(!ValidateBonus()){
                return false;
            }
        }
        /*var bxCount=0;
        var bxNumber=LVMAMA.order.ticket.calbaoxianPersonCount();
        $("dl.user_dl.bx_check dd label input[type=checkbox]:checked").each(function(i){
            bxCount=parseInt(bxCount)+parseInt(1);
        });
        if(bxCount!=bxNumber){
            LVMAMA.order.ticket.showErrorInfo(true,"被保险人与购买的保险数量不一致。");
            return;
        }*/

        if( $("#checkCodeValid").length>0){
            $("#checkCode2").val($("#pic_checkCode").val());
           $.ajax({
                url: "/scenic_front/pic/checkPic",
                data: {pic_checkCode:$("#pic_checkCode").val(),uid:new Date().getTime()},
                async:false,
                success: function(result){
                    if(result=='success'){
                        $("#pic_checkCode").attr("disabled", "true");
                        $("#checkCodeValid").val(1);
                    }
                }
            });
            if( $("#checkCodeValid").val()!='1'){
                LVMAMA.order.ticket.showErrorInfo(true,"请您输入正确的图形验证码。");
                return;
            }
        }

        if($(".promotionMap").size()>0) {
            if(!checkPromotionList()){
                return;
            }
        }
        if(!checkOrderForPayOther()){
            return;
        }
        //发票寄送地址校验
        if(!checkInvoiceAddressInfo()){
        	LVMAMA.order.ticket.showErrorInfo(true,"请选择寄送地址！");
        	 return;
        }
        //限购校验
        if(!checkPromLimit()){
            return;
        }

        //短信验证码验证
        if( $("#msgCode").length>0&&$("#msgCode").is(":visible")){
            LVMAMA.order.ticket.ajaxValidCode($("#msgCode"),function () {
                //库存校验
                if($("div.payBox a.js_tijiao").attr('submitFlag')=="true"){
                    if(isCircusFlag()){
                        $.post("/scenic_front/book/ajax/checkStock.do",getFormData(),function(data){
                            if(data.success){
                                supplierCheckAndSubmit();
                            }else{
                                //库存余量不足
                                var $warningDom = "<div class=\"d_alertError d_alertBox\"><span class=\"tip-icon-big tip-icon-big-warning\"></span><em>当前余量不足，请选择其他日期或场次。</em></div>";
                                showDialog($warningDom);

                                $(".ticketLi:visible .js_input").each(function(){
                                    var goodsId=$(this).attr("goodsId");
                                    var mainItem=$(this).attr("mainItem");
                                    if(mainItem=="true"){
                                        var option = $('.js_select_circus option:selected');
                                        $("input[name='itemMap["+goodsId+"].circusActInfo.circusActId']").val("");
                                        $("input[name='itemMap["+goodsId+"].circusActInfo.circusActStartTime").val("");
                                        $("input[name='itemMap["+goodsId+"].circusActInfo.circusActEndTime").val("");
                                    }
                                });

                                return;
                            }
                        },"JSON");
                    }else{
                        supplierCheckAndSubmit();
                    }
                }
            });
            return;
        }
        //当不用验证短信验证码时验证库存
        if($("div.payBox a.js_tijiao").attr('submitFlag')=="true"){
            if(isCircusFlag()){
                $.post("/scenic_front/book/ajax/checkStock.do",getFormData(),function(data){
                    if(data.success){
                        supplierCheckAndSubmit();
                    }else{
                        //库存余量不足
                        var $warningDom = "<div class=\"d_alertError d_alertBox\"><span class=\"tip-icon-big tip-icon-big-warning\"></span><em>当前余量不足，请选择其他日期或场次。</em></div>";
                        showDialog($warningDom);

                        $(".ticketLi:visible .js_input").each(function(){
                            var goodsId=$(this).attr("goodsId");
                            var mainItem=$(this).attr("mainItem");
                            if(mainItem=="true"){
                                var option = $('.js_select_circus option:selected');
                                $("input[name='itemMap["+goodsId+"].circusActInfo.circusActId']").val("");
                                $("input[name='itemMap["+goodsId+"].circusActInfo.circusActStartTime").val("");
                                $("input[name='itemMap["+goodsId+"].circusActInfo.circusActEndTime").val("");
                            }
                        });

                        return;
                    }
                },"JSON");
            }else{
                supplierCheckAndSubmit();
            }
        }



    }
}
//校验隐藏的元素
function checkDisplayNoneElement(){
	var bankNumberReg = /^[0-9]{10,25}$/;
	var bankNumberInput = $('input[name="invoiceInfo.accountBankAccount"]').val();
	if(undefined != bankNumberInput && bankNumberInput != '' && !bankNumberReg.test(bankNumberInput)){
		if (!$(".btn_invoice_more").hasClass('invoice_more_show')) {
			$(".btn_invoice_more").html('收起<i class="icon_arrow"></i>').addClass('invoice_more_show');
			$(".btn_invoice_more").siblings('.orderDl').show();
		}
		return false;
    }
    return true;
}

//验证礼品卡
function verifyLPKAndSubmit() {

    var _user_bind_result=$("#user_bind_result").val();
    if(_user_bind_result!="bind"){
        //展示去绑定
        $("#ticketRiskAuthDl").hide();
        $("#noLpkBindMobile").show();
        $("#msg_auth_code_div").show();
        return  false;
    }else{
        $("#ticketRiskAuthDl").show();
        $("#noLpkBindMobile").hide();
    }
    var _riskAuthCode = $("#riskAuthCode").val();
    if (_riskAuthCode == "" || _riskAuthCode == undefined) {//未输入短信验证码,显示短信验证码填写框
        riskGiftCard("Y");
    } else {
        //验证短信验证码
        $.getJSON("https://login.lvmama.com/nsso/ajax/validateRiskAuthenticationCode.do?jsoncallback=?", {
            authenticationCode: _riskAuthCode
        }, function (json) {
            if (json.success == true) {//验证成功
                $("#riskAuthCodeError").hide();
                $("#riskAuthCodeInfo").show();
                validedFinalSubmit();
            } else {//验证失败
                $("#riskAuthCodeError").show();
                $("#riskAuthCodeInfo").hide();
            }
        });
    }
}
function riskGiftCard(){
    //礼品卡风控
    var userNo = $("#login_user_no").val();
    var cardNosJson={};
    var categoryId = $("#categoryId").val();
    var goodsQuantity = getTotalQuantity();
    var giftCardFlag = arguments[0];
    $(".lpk_table").find("tr").each(function(index){
        if(index>0){
            var cardNoName = "giftCardList["+(index-1)+"].cardNo";
            var cardNo = $(this).find("input[name='"+cardNoName+"']").val();
            var giftCardAmt = $(this).find(".giftCardAmt").val();
            if(giftCardAmt>0){
                cardNosJson[cardNo] = giftCardAmt;
            }
        }
    });
    if(!$.isEmptyObject(cardNosJson)){
        $.ajax({
            url: 'http://pay.lvmama.com/payment/pay/cardPaymentServiceWithRiskCode.do?jsonCallback=?',
            type: 'GET',
            dataType: 'jsonp',
            data: {
                userNo:userNo,
                cardNosJson:JSON.stringify(cardNosJson),
                orderId:0,
                categoryId: categoryId,
                goodsQuantity: goodsQuantity
            },
            timeout: 1000,
            success: function (result) {
                if(result && ("BLOCK"==result.code)){
                    location.href = "/scenic_front/error/page.do?errorMsg=" + encodeURIComponent(encodeURIComponent("您的账户存在异常，预定失败，如有疑问请联系客服。"));
                }else{
                    $("#noLpkBindMobile").hide();
                    $("#msg_auth_code_div").show();
                }
            },
            error: function () {
                $("#noLpkBindMobile").hide();
                $("#msg_auth_code_div").show();
            }});
    }else{
        $("#noLpkBindMobile").hide();
        $("#msg_auth_code_div").show();
    }
    if(giftCardFlag){
        $("#msg_auth_code_div").attr("data-giftCardFlag",giftCardFlag);
    }else{
        $("#msg_auth_code_div").removeAttr("data-giftCardFlag");
    }
}

var categoryMap = {"11": "景点门票", 12: "其他票", 13: "组合套餐票"};
var order_price_actual_payment = 0;
function validedFinalSubmit(){
    var aperiodicFlag = $("#aperiodicFlag").val();
    var aperiodPackageFlag = $("#aperiodPackageFlag").val();
    if(!(aperiodicFlag == 'Y' || aperiodPackageFlag == 'Y')){
        $("#visitTimeInput").val($('#showVisitTimeInput').val());
    }
    ticketOrderSubmitFlag=true;
    $("form[name='orderForm']").submit();
    ticketOrderSubmitFlag=false;
    //神策埋点
    sensors.track("TicketSubmitOrderAction", {
        current_page: window.location.href,
        product_id: $('#productIdTxt').val(),
        product_first_category: "门票",
        product_second_category: categoryMap[$('#categoryId').val()],
        order_price: ticketPriceinfoData.attributes.price,
        order_price_actual_payment: order_price_actual_payment,
        order_travel_date: $('#visitTimeInput').val(),
        coupon_total_price: ticketPriceinfoData.attributes.price - order_price_actual_payment,
        insurance_total_price: ticketPriceinfoData.attributes.priceInfo.insurancePrice / 100,
        is_use_insurance: isSelectedInsurance(),
        is_need_invocie: $('#isNeedInvoice').val() === 'Y'
    });
}

function finalSubmit(){
    var couponExclusionType=$('.couponExclusionType');
    if(couponExclusionType&&couponExclusionType.length>0){
        if(couponExclusionType.val()==1){//互斥选择促销
            $("#youhuiBox").find("input[name^='userCouponVoList']").remove();
        }else if(couponExclusionType.val()==2){//互斥选择优惠券
            $("#cuxiaoBox").find("input[name^='promotionMap']").remove();
        }
    }else {
        if(couponExclusion && usePromotion){
            $("input[name^='userCouponVoList']").remove();
        }
        if(couponExclusion && useCoupon){
            $("input[name^='promotionMap']").remove();
        }
    }

    //add LPK check
    var lpkCardAmt=$(".giftCardAmt");
    if(null!=lpkCardAmt && lpkCardAmt!=undefined && lpkCardAmt.length>0){
        var lpkAmtTotal=0;
        lpkCardAmt.each(function(){
            if($(this).val()!=""&&$(this).val()!=null)
            {
                lpkAmtTotal+=parseFloat($(this).val());
            }
        });
        if(lpkAmtTotal&&lpkAmtTotal>0){
            verifyLPKAndSubmit();
        }else{
            validedFinalSubmit();
        }
    }else{
        validedFinalSubmit();
    }
}

function checkInvoiceAddressInfo(){
	//var invoiceTypeVal = $("input[name='invoiceInfo.invoiceType']:checked").val();
	if("Y" == $("#isNeedInvoice").val() && isSelectedInsurance() && $('#invoice_insurance_check').attr("checked")){
		var currentLi = $('.invoice_address_list li.active');
		if(currentLi.size() == 1){
			//有选择寄送地址
			return true;
		}else{
			return false;
		}
	}else{
		return true;
	}
}
//是否选择保险
function isSelectedInsurance(){
    var bxGoodsIdList=[];
    $("ul.js_bxtab li.active").each(function(){
        var bxGoodsId=$(this).attr("data-id");
        if(bxGoodsId != undefined){
            bxGoodsIdList.push(bxGoodsId);
        }
    });
    if(bxGoodsIdList.length>0){
        return true;
    }else if($(".js_bx_checkbox").hasClass('checked')){
        return true;
    }else{
        return false;
    }
}

function supplierCheckAndSubmit(){
    //供应商限购
    if($("#supplierCheckFlag").val()=="Y"){
        var addMoreTicket = false;
        $("#mainOtherTicketDiv").find(".ordeRoomNum").each(function(){
            if($(this).val()>=1){
                addMoreTicket = true;
                return false;
            }
        });
        if(!addMoreTicket){
            $.post("/scenic_front/book/ajax/supplierCheck.do",getFormData(),function(data){
                if(data.success){
                    verifyRiskAndSubmit();
                }else{
                    //校验不通过
                    var $warningDom = "<div class=\"d_alertError d_alertBox\"><span class=\"tip-icon-big tip-icon-big-warning\"></span><em>"+data.message+"</em></div>";
                    showDialog($warningDom);
                    return;
                }
            },"JSON");
        }else{
            verifyRiskAndSubmit();
        }
    }else{
        verifyRiskAndSubmit();
    }
}

//获取总份数
function getTotalQuantity() {
    var totalQuantity = 0;
    $("input[name$='].quantity']").each(function () {
        var quantity = $(this).val();
        totalQuantity += parseInt(quantity);
    });
    return totalQuantity;
}

//验证风控和提交
function verifyRiskAndSubmit() {
    var userNo = $("#login_user_no").val();
    var cash = $(".cashAmountHidden").val();
    var bonus = $(".bonusAmountHidden").val();
    var categoryId = $("#categoryId").val();
    var goodsQuantity = getTotalQuantity();
    //是否登陆
    if(userNo != null && userNo != undefined) {
        if(cash != null && cash != undefined && cash > 0){//验证余额
            $.ajax({
                url: 'http://pay.lvmama.com/payment/pay/cashValidateAndPayForVstWithRisk.do?jsonCallback=?',
                type: 'GET',
                dataType: 'jsonp',
                data: {
                    userNo: userNo,
                    amount: cash,
                    categoryId: categoryId,
                    goodsQuantity: goodsQuantity
                },
                timeout: 1000,
                success: function (json) {
                    riskControlAndSubmit(json.code);
                },
                error: function () {
                    finalSubmit();
                }
            });
        }else if(bonus != null && bonus != undefined && bonus > 0){//验证奖金
            $.ajax({
                url: 'http://pay.lvmama.com/payment/pay/bonusValidateAndPayForVstWithRiskCode.do?jsonCallback=?',
                type: 'GET',
                dataType: 'jsonp',
                data: {
                    userNo: userNo,
                    amount: bonus,
                    categoryId: categoryId,
                    goodsQuantity: goodsQuantity
                },
                timeout: 1000,
                success: function (json) {
                    riskControlAndSubmit(json.code);
                },
                error: function () {
                    finalSubmit();
                }
            });
        }else {
            finalSubmit();
        }
    }else {
        finalSubmit();
    }
}

//风险管控和提交
function riskControlAndSubmit(_code) {
    if ('SMS' == _code) {//需要验证短信验证码
        var _riskAuthCode = $("#riskAuthCode").val();
        if (_riskAuthCode == "" || _riskAuthCode == undefined) {//未输入短信验证码,显示短信验证码填写框
            riskGiftCard()
        } else {
            //验证短信验证码
            $.getJSON("https://login.lvmama.com/nsso/ajax/validateRiskAuthenticationCode.do?jsoncallback=?", {
                authenticationCode: _riskAuthCode
            }, function (json) {
                if (json.success == true) {//验证成功
                    $("#riskAuthCodeError").hide();
                    $("#riskAuthCodeInfo").show();
                    validedFinalSubmit();
                } else {//验证失败
                    $("#riskAuthCodeError").show();
                    $("#riskAuthCodeInfo").hide();
                }
            });
        }
    } else if ('BLOCK' == _code) {//直接阻断
        location.href = "/scenic_front/error/page.do?errorMsg=" + encodeURIComponent(encodeURIComponent("您的账户存在异常，预定失败，如有疑问请联系客服。"));
    } else {
        finalSubmit();
    }
}

//检查组合下单票拆分日期
function checkSplitTicketDate(){
	var wflag = true;
	$(".splitcalendar").each(function(index){
        var flag = $(this).attr("ischecked");
        var goodsId = $(this).attr("goodsid");
        if(flag == "N"){
        	$("#error_text"+goodsId).attr("style","display:inline-block");	
        	wflag = false;  
        	return false;
        }        
    });
	return wflag;
}

function checkTicketTypeInfor(){

    var travNumType = $("#travNumType").val();
    var occupType = $("#occupType").val();

    //如果下单项不是全部游玩人或者下单中人群信息不是全部游玩人就不需要校验
    if(travNumType != "TRAV_NUM_ALL" || occupType != "TRAV_NUM_ALL"){
        return true;
    }

    var childTotal = 0;//门票选择的儿童的总份数乘以总人数
    $(".ticketLi:visible .js_input").each(function(){
        var childNum=$(this).attr("child");
        var ticketNum = $(this).val();
        childTotal += parseInt(childNum)*parseInt(ticketNum);
    });

    var childWriteInfoNum = 0;//填写游玩人中选择人群为儿童的个数
    $("#Jtenantlist").find("div.user_info.border_t1_dotted").each(function(k,v){
        var peopleType = $("input[name=\"travellers["+k+"].peopleType\"]:checked").val();
        if(peopleType == 'PEOPLE_TYPE_CHILD'){
            childWriteInfoNum = parseInt(childWriteInfoNum)+1;
        }
    });

    if(childTotal != childWriteInfoNum){
        alert("由于订单中出行儿童数是"+childTotal+"人，请在用户信息板块的“人群”选项上，正确选择 成人 或者 儿童！");
        return false;
    }else{
        return true;
    }
}

function isCircusFlag(){
    return $("#circusFlag").val();
}

function isDisneyShowFlag(){
    return $("#disneyShowFlag").val();
}

function ValidateBonus(){
	$("#bonus_error_msg").html('');
	$("#bonus_error_msg").css("display","none");
	var bonus = $("#bonus_number").val();
	var re = /^(\d+\.\d{1,2}|\d+)$/
	if(bonus==""){
		//$("#target").val("");
		$("#bonus_number").val(0.00);
		return true;
	}
	if(!re.test(bonus)){
		$("#bonus_error_msg").html('<i class="tip-icon tip-icon-error"></i>输入奖金抵扣格式不正确');
		$("#bonus_error_msg").css("display","block");
		$("#target").val("");
		return false;
	}
	if(parseFloat(bonus)>parseFloat(maxBonus)){
		$("#bonus_error_msg").html('<i class="tip-icon tip-icon-error"></i>奖金抵扣额度不能超过最大抵扣额度');
		$("#bonus_error_msg").css("display","block");
		$("#target").val("");
		return false;
	}
	return true;
}

function getVisitTime(){
	var visitTimeInput = $('#visitTimeInput');
	if (visitTimeInput.val() == '') {
		return visitTimeInput.attr('data');
	} else {
		return visitTimeInput.val();
	}
}

function getFormData() {
	var serializeData = $("form[name='orderForm']").serialize();
	var visitTimeInput = $('#visitTimeInput');
	var visitTime = visitTimeInput.val();
	if (visitTime == visitTimeInput.attr('placeHolder') || visitTime == '') {
		serializeData = serializeData.replace('visitTime=', 'visitTime='+visitTimeInput.attr('data'));
	}
	return serializeData;
}

function checkPromotionList(){
	
	var flag=true;

	$.ajax({
		type : "post",
		url : "/scenic_front/book/ajax/checkPromotionList.do",
		data: getFormData(),
		dataType: "json",
		async : false,
		success : function(data){
			if(data.success){
				if(data.attributes.pomMessage!=""){
					LVMAMA.order.ticket.calcPriceInfo();
					pandora.dialog({
						content: "亲，您下手慢了<b>"+data.attributes.pomMessage+"</b>已抢光，如有用户未支付，您可继续参加此活动。",
						//ok: function(){$('div.fk_box a.btn_fk').click();},
						//cancel: true,
						button: [{
							value: "继续",
							className: "pbtn-orange", // 可选btn参数：默认白色 pbtn-pink btn-porange pbtn-blue
							callback: function () {$('div.payBox a.js_tijiao').click();}
							},{
								value: "放弃",
								className: "pbtn-orange", // 可选btn参数：默认白色 pbtn-pink btn-porange pbtn-blue
								callback: function () {}
								}]
						});
					flag=false;
				}
			}else{
					LVMAMA.order.ticket.calcPriceInfo();
					pandora.dialog({
						content: "亲，服务器走神了，促销校验失败，无法使用促销优惠，确认继续购买？",
						//ok: function(){$('div.fk_box a.btn_fk').click();},
						//cancel: true,
						button: [{
							value: "继续",
							className: "pbtn-orange", // 可选btn参数：默认白色 pbtn-pink btn-porange pbtn-blue
							callback: function () {$('div.payBox a.js_tijiao').click();}
							},{
								value: "放弃",
								className: "pbtn-orange", // 可选btn参数：默认白色 pbtn-pink btn-porange pbtn-blue
								callback: function () {}
								}]
						});
					flag=false;
			}
		}
	});
	return flag;
}


function checkStock(){
	if(!LVMAMA.order.ticket.orderValidate()){
        disableSubmitButton();
		return;
	}
	cleanPromotion();
    disableSubmitButton();
	$.post("/scenic_front/book/ajax/checkStock.do",getFormData(),function(data){
        enableSubmitButton();
		if(!data.success){
            LVMAMA.order.ticket.fillOrderInfo();
			//需要提示库存不足
			showAmountInfo({"success":false});
			LVMAMA.order.ticket.showErrorInfo(true,data.message);
			
		}else{
			LVMAMA.order.ticket.calcPriceInfo();
			LVMAMA.order.ticket.showErrorInfo(false,"");
		}
	},"JSON");
	LVMAMA.order.ticket.getTicketGoodsRebateAmount();
}
//多园多日需要先校验库存，再继续后续操作
function calendarConfirmCallbackForParkDays(){
	if(!LVMAMA.order.ticket.orderValidate()){
        disableSubmitButton();
		return;
	}
	cleanPromotion();
    disableSubmitButton();
	$.post("/scenic_front/book/ajax/checkStock.do",getFormData(),function(data){
        enableSubmitButton();
		if(!data.success){
            LVMAMA.order.ticket.fillOrderInfo();
			//需要提示库存不足
			showAmountInfo({"success":false});
			if(data.message.indexOf('库存不足')>-1){
				var $price = $(".price-change-dialog-mask");
		        $price.show();
			}else{
				LVMAMA.order.ticket.showErrorInfo(true,data.message);
			}
			
		}else{
			calendarConfirmCallback.invoke();
		}
	},"JSON");
}

//限购校验
function checkPromLimit(){
    var flag=true;
    $.ajax({
        type : "post",
        url : "/scenic_front/book/ajax/checkPromLimit.do",
        data: getFormData(),
        dataType: "json",
        async : false,
        success : function(data){
            if(data&&data.code){
                if(data.code=="error"){
                    LVMAMA.order.ticket.showErrorInfo(true,data.message);
                    flag=false;
                }
            }else{
                LVMAMA.order.ticket.showErrorInfo(true,"亲，服务器走神了，请重新尝试。");
                flag=false;
            }
        }
    });
    return flag;
}

var ajaxCallNum = 0;

function disableSubmitButton() {
    ajaxCallNum = ajaxCallNum +1;
    $("div.payBox a.js_tijiao").addClass('btn-forbidden').removeClass('btn-orange').attr('submitFlag','false');
}

function enableSubmitButton() {
    ajaxCallNum = ajaxCallNum -1;
    if(ajaxCallNum == 0){
        $("div.payBox a.js_tijiao").removeClass('btn-forbidden').addClass('btn-orange').attr('submitFlag','true');
    }
}


function formatDateStr(x,y) {
	var z = {M:x.getMonth()+1,d:x.getDate(),h:x.getHours(),m:x.getMinutes(),s:x.getSeconds()};
	y = y.replace(/(M+|d+|h+|m+|s+)/g,function(v) {return ((v.length>1?"0":"")+eval('z.'+v.slice(-1))).slice(-2)});
	return y.replace(/(y+)/g,function(v) {return x.getFullYear().toString().slice(-v.length)});
}



//显示买赠信息
function showBuyPresentActivityInfo(data){
	cleanBuyPresentActivityInfo();
	if(data.success){
		var buyPersent=data.attributes.buyPersentActivity;
		if(buyPersent&&buyPersent.presents){
			var order_zp =$(".gift");
			//处理买赠是否提示不满足信息
			
			//循环处理赠品
			var presents=buyPersent.presents;
            var appendHtml="";
			if(presents){
				$.each(presents, function(k,item){
					var expStr=item.presentName+"&emsp;x&emsp;"+item.sendCount;
					if(item.presentExpireStart && item.presentExpireEnd){
						expStr+="&emsp;有效期："
						+formatDateStr(new Date(item.presentExpireStart),"yyyy.MM.dd")+"&emsp;-&emsp;"+
									formatDateStr(new Date(item.presentExpireEnd),"yyyy.MM.dd");
						
					}
                    appendHtml+=("<li>"+expStr+"</li>");
				});
                order_zp.find(".gift-list").empty();
                order_zp.find(".gift-list").append(appendHtml);
			}

            if(buyPersent.isFulfil=='N'){
                order_zp.hide();
            }else{
                order_zp.show();
            }
		}
		
		
		
	}
}


function cleanBuyPresentActivityInfo(){
	var order_zp =$(".order_zp");
	order_zp.find(".zp-dd").html("");
	order_zp.hide();

}

function showAmountInfo(data){
	if(data.success){
		showAmountInfoNew(data);
	}else{
		$(".maxCanPayBouns").html((0).toFixed(2));
		$(".maxpayBounsAmt").val(0);
		$(".rebateAmountSpan").html((0).toFixed(2));
		$(".rebateAmountSpan").html((0).toFixed(2));
		$(".fk_box_free").find(".oughtPay").html("--");
		$(".fk_box_free").find(".oughtPayHidden").val(0);
		$(".fk_box_fixed").find(".orderamountPage").html("--");
	}
}

//弹出登录框
function openLoginWindow(){
	//判断登陆
	$.getJSON(
		"http://login.lvmama.com/nsso/ajax/checkLoginStatus.do?jsoncallback=?",
		{},
		function(data) {
			if (!data.success) {
				isOrNotJumpToUrl = false;
				showRadidLoginDiv();
			}
		}
	);
}

function loginFormSubmit(){
	$(".dialog-close").click();
	$.post("/scenic_front/book/ajax/queryCurrentLoginUser.do", {},function(data){
		if(data.success) {
			if(data.attributes != null && data.attributes.user && data.attributes.user.userName) {
				$(".welcome").html("您好，<b>" + data.attributes.user.userName + "</b>");
				$("#bonusMsgDiv").css("display", "");
				if($("#picCodeContainer") && $("#picCodeContainer").length>0){
					$("#picCodeContainer").remove();
				}
				clickCouponVerify($("#couponVerifySpan"));
				queryRelatedContactPerson();
			}
		}
	});
}

function notNullStr(srcStr) {
	if(srcStr == null || srcStr == 'null') {
		return '';
	}
	
	return srcStr;
}

//查询常用联系人并显示到页面
function queryRelatedContactPerson() {
	$.post("/scenic_front/book/ajax/queryRelatedContactPerson.do", {},function(data){
		if(data.success) {
			if(data.attributes != null && data.attributes.personList != null && data.attributes.personList.length > 0) {
				var personContent = "<b>常用联系人：</b>";
				$(data.attributes.personList).each(function(idx, currPerson){
					if(currPerson!=null){
						personContent += '<label class="check">' +
											'<input class="checkbox" type="checkbox" value="' + notNullStr(currPerson.receiverId) +
											'" name="contactsPersonCheckbox" personName="' + notNullStr(currPerson.fullName) +
											'" firstName="' + notNullStr(currPerson.firstName) + '" lastName="' + notNullStr(currPerson.lastName) +
											'" peopleType="' + notNullStr(currPerson.peopleType) + '" mobile="' + notNullStr(currPerson.mobile) +
											'" idNo="' + notNullStr(currPerson.idNo) + '" idType="' + notNullStr(currPerson.idType) +
											'" email="' + notNullStr(currPerson.email) + '">' + notNullStr(currPerson.fullName) + '</label>';
					}
				});
				$("#commonlyUsed").html(personContent);
				
				//绑定事件
				FRONT.book.user.travellersBindEvent();
			}
		}
	});
}

//回调接口
function callback(){
	this.funs = [];
	this.pushFun = function(fun) {
		this.funs.push(fun);
	};
	this.invoke = function() {
		for (var i = 0; i < this.funs.length; i++) {
			try {
				this.funs[i]();
			} catch (err) {
				alert(err);
				return false;
			}
		}
	};
}

//刷新价格
function refereshTimePrice(){
	var visitTime=getVisitTime();
	var productIds="";
	var goodsIds="";
    $(".ticketLi:visible .js_input").each(function(i){
		var integerReg = "^[0-9]*[0-9][0-9]*$";
		if($.trim($(this).val()).match(integerReg)){
			var goodsId=$(this).attr("goodsId");
			var productId=$(this).attr("productId");
			if(goodsId!=undefined){
				goodsIds+=goodsId+",";
			}
			if(productId!=undefined){
				productIds+=productId+",";
			}
		}
	});
	if($.trim(visitTime)==""){
		return;
	}
    disableSubmitButton();
    $.ajax({
        type : "post",
        url : "/scenic_front/book/ticket/refereshTimePrice.do",
        data : {
            visitTime:visitTime,
            productIds:productIds,
            suppGoodsIds:goodsIds
        },
        async : false,
        success : function(data){
            if(data.success){
                $(data.attributes.ticketVoList).each(function(k,v){
                    $(".ticketLi:visible .js_input").each(function(){
                        var goodsId=$(this).attr("goodsId");
                        if(v.suppGoodsId==goodsId){
                            if(v.suppGoodsAddTimePrice!=null){
                                $(this).attr("price",v.suppGoodsAddTimePrice.price);
                            }
                        }
                    });
                });
                var ticketProductVO =data.attributes.ticketProductVO;
                if(ticketProductVO!=null){
                    $(".ticketLi:visible .js_input").each(function(){
                        var productId=$(this).attr("productId");
                        if(ticketProductVO.product.productId==productId){
                          $(this).attr("price",ticketProductVO.totalPrice);
                        }
                    });
                }
            }
        },
        complete:function(){
            enableSubmitButton();
        }
    });
}


//刷新组合拆分价格
var goodMap = null;
function refereshSplitTimePrice(suppGoodsId,isInstall){	
	var visitTime=getVisitTime();
	var productIds="";
	$(".ticketLi:visible .js_input").each(function(i){
		var integerReg = "^[0-9]*[0-9][0-9]*$";
		if($.trim($(this).val()).match(integerReg)){
			var productId=$(this).attr("productId");
			if(productId!=undefined){
				productIds+=productId+",";
			}
		}
	});
	if(goodMap == null || isInstall == 'N'){
	    $.ajax({
	        type : "post",
	        url : "/scenic_front/book/ticket/refereshSplitTimePrice.do",
	        data : {
	            visitTime:visitTime,
	            productIds:productIds,
	            suppGoodsId:suppGoodsId
	        },
	        async : false,
	        success : function(data){
	            if(data.success){
	                var ticketProductVO =data.attributes.ticketProductVO;
	                goodMap = ticketProductVO.goodsIdAspriceMap;
	                if(ticketProductVO!=null){
	                    $(".ticketLi:visible .js_input").each(function(){
	                        var productId=$(this).attr("productId");
	                        if(ticketProductVO.product.productId==productId){ 	                        	                        	
	                        	for (var key in goodMap) { 
	                        		if(key == suppGoodsId){
	                        		  opElementFunction({id:key,value:goodMap[key]},$(this)); 
	                        		}
	                            }  	
	                        }
	                    });
	                }
	            }
	        }
	    });
	}else if(goodMap != null){
		$(".ticketLi:visible .js_input").each(function(){
            	for (var key in goodMap) { 
            		if(key == suppGoodsId){
            		   opElementFunction({id:key,value:goodMap[key]},$(this)); 
            		}
                }  	
        });
	}
}

var opElementFunction = function(){
	var  items= [];
	var flag = true;
	function put(obj,$obj){	
		for(var i=0;i<items.length;i++){
			if(items[i].id == obj.id){
				items[i].value = obj.value;
				flag = false;			
				break;		
			}			
		}
		if(flag){
			items.push(obj);				
		}		
		var totalPrice = 0.0;
		for(var i=0;i<items.length;i++){
			totalPrice += items[i].value;	
		}	
		$obj.attr("price",totalPrice);
	}	
	return put;
}();
     

function showExpressCheck(){
	var showFlag=false;
    $(".ticketLi:visible .js_input").each(function(i){
		var num=$(this).val();
		var goodsType=$(this).attr("goodsType");
		if(LVMAMA.order.ticket.isTrueNumber(num)){
			if(goodsType=="EXPRESSTYPE_DISPLAY"){
				showFlag=true;
				return false;
			}
		}
	});
	
	if (! showFlag) {
		var checkedBxRadio = $("ul.bx_list").find("li.bx_list1 input[type=radio]:checked");
		var bxNumInput = checkedBxRadio.parents('li.bx_list').find("li.bx_list3 input[type=text]");

		if(LVMAMA.order.ticket.isTrueNumber($.trim(bxNumInput.val())) && bxNumInput.attr("goodsType")=="EXPRESSTYPE_DISPLAY"){
			return true;
		}
	}
	
	return showFlag;
}

function selectSuppGoodsLastStyle(){
    var num = $(".ticketLi:visible").length;

    $(".ticketLi:visible").each(function(i){
        //更改最后一个商品的样式
        if(i == num-1){
            $(this).addClass("last");
        }else{
            $(this).removeClass("last");
        }
    });
}

//预订数量变更后的回调接口
var bookNumOnchangeCallback = new callback();
//日期确定后的回调接口
var calendarConfirmCallback = new callback();
//选择保险确定后回调接口
var bxOnchangeCallback = new callback();
//用户信息
var userInfos = new Array();
//用户选择商品
var select_goodsIds = new Array();
//用户选择商品但未确定
var temp_select_goodsIds = new Array();

var ticketPriceinfoData;
var firstCalAmt;
calendarConfirmCallback.pushFun(function () {
    LVMAMA.order.ticket.isCalendarConfirmCallback=true;
});
var LVMAMA={
		order: {
            ticket: {
                orderValidate: function () {
                    var noError = true;
                    $('a.orderAdd').each(function (i, v) {
                        var num = $(v).siblings("input[type=text]").val();
                        var mainItem = $(v).siblings("input[type=text]").attr("mainItem");
                        if (LVMAMA.order.ticket.notNumber(num) && mainItem == "true") {
                            //提示
                            noError = false;
                            return false;
                        }
                    });
                    return noError;
                },
                infoHtml: function (This, text) {
                    This.addClass('yz_error').siblings('.error_text').css('display', 'inline-block').html('<i class="tip-icon tip-icon-info"></i>' + text + '。').siblings('.ts_text').hide();
                },
                //获取马戏票场次信息
                getCircusInformation: function () {
                    $('.d_ccLoading').show();
                    $('.d_ccNull').hide();
                    $('.js_select_circus').prev('div').hide();
                    var date = $("#showVisitTimeInput").val();
                    if(date == ""){
                        date = $("#visitTimeInput").val();
                    }
                    var suppGoodsId;
                    $("dd.orderNumBox input").each(function () {
                        var goodsId = $(this).attr("goodsId");
                        var mainItem = $(this).attr("mainItem");
                        if (mainItem == "true") {
                            suppGoodsId = goodsId;
                            if ($("#circusFlag").val()) {
                                $(this).attr("stockQuantity", 0);
                                disableSubmitButton();
                                $.ajax({
                                    url: "/scenic_front/book/ticket/refereshCircusInformation.do",
                                    data: {
                                        suppGoodsId: suppGoodsId,
                                        visitTime: date
                                    },
                                    async: false,
                                    success: function (result) {
                                        $('.d_ccLoading').hide();
                                        $('.js_select_circus option').remove();
                                        if (result.length > 0) {
                                            var circusInformation = "<option selected='selected' disabled='true'>-请选择场次-</option>";
                                            for (var i = 0; i < result.length; i++) {
                                                var circusActId = result[i].circusActId;
                                                var circusActStartTime = result[i].circusActStartTime;
                                                var circusActEndTime = result[i].circusActEndTime;
                                                if (circusActId && circusActStartTime && circusActEndTime) {
                                                    circusInformation += "<option data-id='" + circusActId + "' start-time='" + circusActStartTime + "' end-time='" + circusActEndTime + "'>" + circusActStartTime.split(" ")[1] + "——" + circusActEndTime.split(" ")[1] + "</option>";
                                                } else if (circusActEndTime == null || circusActEndTime == "") {
                                                    circusInformation += "<option data-id='" + circusActId + "' start-time='" + circusActStartTime + "' end-time=''>" + circusActStartTime.split(" ")[1] + "场次</option>";
                                                }
                                            }
                                            $('.js_select_circus').show();
                                            $('.js_select_circus').append(circusInformation);
                                            pandora.selectModel({'autoWidth': false, 'selectElement': $('.js_select_circus')});
                                        } else {
                                            $('.d_ccNull').show();
                                        }
                                    },
                                    complete:function(){
                                        enableSubmitButton();
                                    }
                                });
                            }
                            return;
                        }
                    });
                },
                //获取马戏票库存信息
                getCircusStock: function () {
                    var suppGoodsId;
                    $("dd.orderNumBox input").each(function () {
                        var goodsId = $(this).attr("goodsId");
                        var mainItem = $(this).attr("mainItem");
                        if (mainItem == "true") {
                            suppGoodsId = goodsId;
                            return;
                        }
                    });
                    var circusId = $('.js_select_circus option:selected').attr('data-id');
                    var circusCount;
                    $.ajax({
                        url: "/scenic_front/book/ticket/getCircusStock.do",
                        data: {
                            suppGoodsId: suppGoodsId,
                            circusId: circusId,
                            visitTime: $("#visitTimeInput").val()
                        },
                        async: false,
                        success: function (result) {
                            circusCount = result;
                            $(".ticketLi:visible .js_input").each(function () {
                                var mainItem = $(this).attr("mainItem");
                                if (mainItem == "true") {
                                    $(this).attr("stockQuantity", circusCount);
                                    return;
                                }
                            });
                        }
                    });
                    return circusCount;
                },
                bookNumOnchangeComm: function (o, operator) {
                    var obj = $(o);

                    var ticketType = $(obj).siblings("input[type=text]").attr("ticketType");
                    /*if(operator=="+" && ticketType == "DISNEY_TICKET"){
                     var msg = LVMAMA.order.ticket.checkTotalNumDisneyTicket();
                     if(msg != ""){
                     $.alert(msg);
                     return;
                     }
                     }*/

                    var num = $(obj).siblings("input[type=text]").val();
                    var min = parseInt($(obj).siblings("input[type=text]").attr("minQuantity"));
                    //获取马戏票的库存
                    var circusStock = parseInt($(obj).siblings("input[type=text]").attr("stockQuantity"));
                    var max = parseInt($(obj).siblings("input[type=text]").attr("maxQuantity"));
                    max = max > circusStock ? circusStock : max;
                    var mainItem = $(obj).siblings("input[type=text]").attr("mainItem");
                    if (LVMAMA.order.ticket.notNumber(num)) {
                        num = 0;
                    }
                    num = parseInt(num);

                    if (operator == "+" && num < max) {
                        num++;
                        if (ticketType == "DISNEY_TICKET") {
                            var goodsid = $(o).parent().find('input').attr('goodsid');
                            var msg = LVMAMA.order.ticket.checkTotalNumDisneyTicket(num, goodsid);
                            if (msg != "") {
                                $.alert(msg);
                                return;
                            }
                        }
                    } else if (operator == "-" && num > min) {
                        num--;
                    }

                    if (num < min) {
                        if (operator == '-') {
                            if (mainItem == "false'") {
                                num = 0;
                            } else if (mainItem == "true") {
                                num = min;
                            }
                        } else if (operator == '+' && mainItem == "false") {
                            num = min;
                        }
                    }

                    if (num > min && num < max && mainItem == "true" || num > 0 && mainItem == "false"&& num < max) {
                        if (operator == "+") {
                            $(obj).siblings('a.orderReduce.num_stop').removeClass('num_stop');
                        } else {
                            $(obj).siblings('a.orderAdd.num_stop').removeClass('num_stop');
                        }
                    } else {
                        $(obj).addClass('num_stop');
                        //if(operator=="-"){
                        //	$(obj).addClass('num_stop');
                        //}else{
                        //	$(obj).siblings('a.num_subtraction').addClass('num_stop');
                        //}
                    }

                    $(obj).siblings('input[type=text]').val(num);

                    if (num > max) {
                        LVMAMA.order.ticket.showInfo(obj, "最多预订数量：" + max);
                    }
                    if (num < parseInt(min) && mainItem == "true") {
                        LVMAMA.order.ticket.showInfo(obj, "至少预订数量：" + min);
                    }

                    LVMAMA.order.ticket.bxNumBussiness();

                    if ($.trim(getVisitTime()) == "" && $("#islvmamaPackge") == null) {
                        return;
                    }
                    //if(parseInt(num)>0){
                    bookNumOnchangeCallback.invoke();
                    //}
                },
                isNumber: function (val) {
                    return val.match("^[0-9]*$");
                },
                notNumber: function (val) {
                    return !this.isNumber(val);
                },
                isTrueNumber: function (val) {
                    return val.match("^[1-9][0-9]*$");
                },
                addTicketProductIds: function (productIds) {
                    $(".js_input").each(function () {
                        if (LVMAMA.order.ticket.isTrueNumber($(this).val())) {
                            var productId = $(this).attr("productId");
                            if (productId != undefined) {
                            	productIds[productId] = $(this).val();
                            }
                        }
                    });
                    return productIds;
                },
                addTicketGoodIds: function (goodsIds) {
                    $(".js_input").each(function () {
                        if (LVMAMA.order.ticket.isTrueNumber($(this).val())) {
                            var goodsId = $(this).attr("goodsId");
                            if (goodsId != undefined) {
                            	goodsIds[goodsId] = $(this).val();
                            }
                        }
                    });
                    return goodsIds;
                },
                addNewTicketGoodIds: function (goodsIds) {
                    $(".js_input").each(function (i) {
                        if (LVMAMA.order.ticket.isTrueNumber($(this).val())) {
                            var goodsId = $(this).attr("goodsId");
                            if (goodsId != undefined) {
                            	goodsIds[i] = {goodsId:goodsId,num:$(this).val()};
                            }
                        }
                    });
                    return goodsIds;
                },
                addBxGoodIds: function (bxGoodsIds) {
                	$("ul.js_bxtab li.active").each(function () {
                		var bxGoodsId=$(this).attr("data-id");
                		if(bxGoodsId != undefined && parseInt(bxGoodsId) != 0&&bxGoodsId!=""){
                		var num = LVMAMA.order.ticket.getInsuranceNum(bxGoodsId);
                		bxGoodsIds[bxGoodsId] = num;
                   	  }	
                	});
                    return bxGoodsIds;
                },
                //点击添加更多门票
                clickOtherMoreGoods: function () {
                    temp_select_goodsIds.length = 0;
                    for (var i = 0; i < select_goodsIds.length; i++) {
                        temp_select_goodsIds.push(select_goodsIds[i]);
                    }

                    $(".addTicket-table dl .pdSelect a").each(function () {
                        if (temp_select_goodsIds.indexOf($(this).attr("data-goods")) < 0) {
                            $(this).html("选择<i class='orderIcon orderIcon_gou'></i>");
                            $(this).removeClass("active");
                        } else {
                            $(this).html("已选<i class='orderIcon orderIcon_gou'></i>");
                            $(this).addClass("active");
                        }
                    });
                },
                //选择商品
                clickChoiceGoods: function (e) {
                    var goodsId = e.attr("data-goods");
                    if (temp_select_goodsIds.indexOf(goodsId) < 0) {
                        e.html("已选<i class='orderIcon orderIcon_gou'></i>");
                        e.addClass("active");
                        temp_select_goodsIds.push(goodsId);
                    } else {
                        e.html("选择<i class='orderIcon orderIcon_gou'></i>");
                        e.removeClass("active");

                        var index = temp_select_goodsIds.indexOf(goodsId);
                        for (var i = index; i < temp_select_goodsIds.length - 1; i++) {
                            temp_select_goodsIds[i] = temp_select_goodsIds[i + 1];
                        }
                        temp_select_goodsIds.pop();
                    }
                },
                //确定选中商品
                clickSelectGoods: function () {
                    select_goodsIds.length = 0;
                    for (var i = 0; i < temp_select_goodsIds.length; i++) {
                        select_goodsIds.push(temp_select_goodsIds[i]);
                    }

                    $(".ticketLi").each(function (index) {
                        var goodsIds = $(this).attr("data-goods");
                        if (!$(this).hasClass("main") && select_goodsIds.indexOf(goodsIds) < 0) {
                            $(this).hide();
                        } else {
                            $(this).show();
                            /*if($(this).find(".js_input").val() == 0){
                             $(this).find(".js_input").val($(this).find(".js_input").attr("minQuantity"));
                             }*/
                        }
                    });
                    selectSuppGoodsLastStyle();
                    bookNumOnchangeCallback.invoke();
                },
                isSelectAllGoods:function(){
                    var res = true;
                    $(".addTicket-table dl .pdSelect a").each(function () {
                        if (!$(this).hasClass("active")) {
                            res = false;
                        }
                    });
                    return res;
                },
                //删除选中的商品
                clickDeleteGoods: function (e) {
                    e.parent().siblings(".orderDl").find("input").val(0);
                    e.parents(".ticketLi").hide();
                    var goodsId = e.parents(".ticketLi").attr("data-goods");
                    var index = select_goodsIds.indexOf(goodsId);
                    for (var i = index; i < select_goodsIds.length - 1; i++) {
                        select_goodsIds[i] = select_goodsIds[i + 1];
                    }
                    select_goodsIds.pop();
                    $(".js_select_goods").each(function () {
                        if (goodsId == $(this).attr("data-goods")) {
                            $(this).html("选择<i class='orderIcon orderIcon_gou'></i>");
                            $(this).removeClass("active");
                        }
                    });

                    selectSuppGoodsLastStyle();
                    bookNumOnchangeCallback.invoke();
                },
                //将页面的用户信息填充到userInfos变量中
                fillUserInfosMap: function () {
                    userInfos = new Array();
                    $("#Jtenantlist").find(".user_info").each(function (i) {
                        $(this).find(".user_dl").each(function (i) {
                            $(this).find("input,select").each(function (i) {
                                var _name = $(this).attr("name");
                                var _value = $(this).val();
                                if (_name != "" && _value != "") {
                                    if ($(this).attr("type") == "radio") {
                                        if ($(this).attr("checked") == "checked") {
                                            userInfos.push({name: _name, value: _value});
                                        }
                                    } else {
                                        userInfos.push({name: _name, value: _value});
                                    }
                                }
                            })
                        });
                    });

                    $("#expressageInfoDiv").find(".user_info").each(function (i) {
                        $(this).find(".user_dl").each(function (i) {
                            $(this).find("input").each(function (i) {
                                var _name = $(this).attr("name");
                                var _value = $(this).val();
                                if (_name != "" && _value != "") {
                                    userInfos.push({name: _name, value: _value});
                                }
                            })
                        });
                    })
                },
                //用userInfos里面的值填充用户信息
                fillUserInfos: function () {
                    $("#Jtenantlist").find(".user_info").each(function () {
                        var num = $(this).attr("index");
                        for (var i = 0; i < userInfos.length; i++) {
                            if (userInfos[i].name == "travellers[" + num + "].idType") {
                                var _idTypeInput = userInfos[i].value;
                                FRONT.book.user.showBirthdayStrAndGender(_idTypeInput, num);
                            }
                        }

                        $(this).find(".user_dl").each(function (i) {
                            $(this).find("input,select").each(function (i) {
                                var _name = $(this).attr("name");
                                if (_name != "") {
                                    for (var i = 0; i < userInfos.length; i++) {
                                        if (userInfos[i].name == _name) {
                                            var _value = userInfos[i].value;
                                            if ($(this).attr("type") == "radio") {
                                                if ($(this).val() == _value) {
                                                    $(this).attr("checked", true);
                                                }
                                            } else {
                                                $(this).val(_value);
                                            }
                                        }
                                    }
                                }
                            })
                        });
                    });

                    $("#expressageInfoDiv").find(".user_info").each(function () {
                        $(this).find(".user_dl").each(function (i) {
                            $(this).find("input").each(function (i) {
                                var _name = $(this).attr("name");
                                if (_name != "") {
                                    for (var i = 0; i < userInfos.length; i++) {
                                        if (userInfos[i].name == _name) {
                                            var _value = userInfos[i].value;
                                            $(this).val(_value);
                                        }
                                    }
                                }
                            })
                        });
                    });
                    LVMAMA.order.ticket.fillUserInfosMap();
                },
                fillSaleRelPrice:function(){
                	var saleRelPrice = 0;
                	$(".orderTicketInfo-list ul").each(function(){
                		if($(this).attr("goodsSaleFlag")=="Y"){
                			saleRelPrice+=parseFloat($(this).attr("data-all-price"));
                		}
                	});
                	return saleRelPrice;
                },
                //填充订单明细
                fillOrderInfo: function () {
                    var goodsPrice = LVMAMA.order.ticket.fillSuppGoodsOrderInfo();
                    var insurancePrice = LVMAMA.order.ticket.fillInsuranceOrderInfo();
                    var orderTicket = LVMAMA.order.ticket.calculateOrderTicketInfo();

                    var expressPrice = LVMAMA.order.ticket.fillExpressPrice();
                    var saleRelPrice = LVMAMA.order.ticket.fillSaleRelPrice();
                    //价格单位是分
                    var totalPrice = goodsPrice + insurancePrice + expressPrice*100 - orderTicket+saleRelPrice*100;
                    var commentPrice = LVMAMA.order.ticket.calculateCommentOrderInfo();
                    
                    if(totalPrice < 0){
                        totalPrice = 0;
                    }
                    $('.ticket_price_cc').html("￥<i>"+goodsPrice/100+"</i>");                 
                    $('.ticketPriceTotal dfn').html("<span class=\"yh\">￥</span>" + totalPrice / 100);
                    order_price_actual_payment = totalPrice / 100;
                    $('.ticketPriceTotal p').remove();
                    if (commentPrice > 0) {
                        $('.ticketPriceTotal dfn').after("<p>点评返现 <span class=\"yh\">￥</span> " + commentPrice + "</p>");
                    }
                },
                fillExpressPrice:function (){
                    if($(".js_express_info")){
                        $(".js_express_info").remove();
                    }
                    if($(".express_price big")&&parseFloat($(".express_price big").html())>0){
                        var expressPrice = parseFloat($(".express_price big").html());
                        var expressPriceHtml = "<ul class=\"js_express_info\">" +
                            "<li class=\"primary\"><em>运费</em><dfn><i>￥</i>" + expressPrice + "</dfn></li>" +
                            "</ul>";
                        $(".orderTicketInfo-list ul:last").before(expressPriceHtml);
                        return expressPrice;
                    }
                    if($(".invoice_express_price big")&&parseFloat($(".invoice_express_price big").html())>0){
                    	var invoiceExpressPrice = parseFloat($(".invoice_express_price big").html());
                        var expressPriceHtml = "<ul class=\"js_express_info\">" +
                            "<li class=\"primary\"><em>运费</em><dfn><i>￥</i>" + invoiceExpressPrice + "</dfn></li>" +
                            "</ul>";
                        $(".orderTicketInfo-list ul:last").before(expressPriceHtml);
                        return invoiceExpressPrice;
                    }
                    return 0;
                },
                //填充商品订单明细
                fillSuppGoodsOrderInfo: function () {
                    //清除商品明细
                    $(".orderTicketInfo-list ul:first li").each(function (i) {
                    	//新增多园多日显示判断
                        if (i != 0&&$(this).attr("id")!='parksName') {
                            $(this).remove();
                        }
                    });

                    var price = 0;
                    $(".ticketLi:visible .js_input").each(function () {
                        if ($(this).val() > 0) {
                            var suppGoodsHtml = "<li><em>" + $(this).attr("suppGoodsName") + "</em><dfn class=\"dark\"><span class=\"f12\">" + $(this).val() + " X <i>￥</i></span>" + $(this).attr("price") / 100 + "</dfn></li>";
                            $(".orderTicketInfo-list ul:first").append(suppGoodsHtml);
                            price = price + $(this).val() * $(this).attr("price");
                        }
                    });

                    //计算门票总价
                    $(".orderTicketInfo-list ul:first .primary dfn").html("<i>￥</i>" + price / 100);
                    return price;
                },
                //填充保险明细
                fillInsuranceOrderInfo: function () {
                    //清除保险明细
                    $(".orderTicketInfo-list .js_insurance").remove();

                    var totalPrice = 0;
                    var insuranceListHtml="";
                    if (LVMAMA.order.ticket.checkSelectedInsurance()) {
                    	$("ul.js_bxtab li.active").each(function () {
                    		var bxGoodsId=$(this).attr("data-id");
                    		if(bxGoodsId != undefined){
                    		var num = LVMAMA.order.ticket.getInsuranceNum(bxGoodsId);
                    		 var price = $(this).attr("data-price");
                             var name="";
                             var  isbacktochangebxflag= $(this).attr('isbacktochangebxflag');
                             if(isbacktochangebxflag=='Y'){
                             	name="赠送退票损失险";
                             }else{
                             	name = $(this).attr("data-name");
                             }
                             totalPrice += num * price;
                             insuranceListHtml+="<li><em>" + name + "</em><dfn class=\"dark\"><span class=\"f12\">" + num + " X <i>￥</i></span>" + price / 100 + "</dfn></li>";
                       	  }	
                    	});
                        var insuranceHtml = "<ul class=\"js_insurance\">" +
                            "<li class=\"primary\"><em>保险</em><dfn><i>￥</i>" + totalPrice / 100 + "</dfn></li>" +insuranceListHtml +"</ul>";
                        $(".orderTicketInfo-list ul:first").after(insuranceHtml);
                    }
                    return totalPrice;
                },
                //计算点评订单价格
                calculateCommentOrderInfo: function () {
                    var price = 0;
                    $(".ticketLi:visible .js_input").each(function () {
                        if ($(this).attr("pc_rebate") != undefined && $(this).attr("pc_rebate") > 0) {
                            price = price + $(this).val() * $(this).attr("pc_rebate");
                        }
                    });
                    price = price>100?100:price;
                    return price;
                },
                //计算优惠抵扣              
                calculateOrderTicketInfo: function () {            	
                	   var price = 0.0;                  
                    var tempArray = LVMAMA.order.ticket.orderTicketInfoArray;
                    var tempHtml = "";
                    var length = tempArray.length;
                    if(length > 0){
                    	for(var i = 0; i < length; i++){
                    		if(tempArray[i].indexOf("促销")>0&&$("#promPromotionDiv").find("input[name^='promotionMap']").length==0){
                    			continue;
                    		}
                    		tempHtml += tempArray[i];
                    	}
                       	 $(".orderTicketInfo-list .last").html(tempHtml);  	                
                    }else{
                    	$(".orderTicketInfo-list .last").html("");
                    }                                                                                       
//                  <li class="primary"><em>促销</em><dfn><i> ¥</i>20</dfn></li>
//                  <li class="primary"><em>优惠券</em><dfn><i> ¥</i>5</dfn></li>
                    price = LVMAMA.order.ticket.toalPrice;
                    return price;
                },
                orderTicketInfoArray:[],     
                toalPrice:0.0,
                isCalendarConfirmCallback:false,//是否重新选择了日期，重新选择日期需要重新获取优惠券。
                //刷新游玩人
                refereshTravellers: function () {
                    disableSubmitButton();
                    var ticketNumber = LVMAMA.order.ticket.calTicketPersonCount();//门票人数 
                    var bxNumber = LVMAMA.order.ticket.calbaoxianPersonCount();
                      var goodsIds ={};
                      var productIds ={};
                      var bxGoodsIds={};
                      productIds = LVMAMA.order.ticket.addTicketProductIds(productIds);
                      goodsIds = LVMAMA.order.ticket.addNewTicketGoodIds(goodsIds);
                      bxGoodsIds = LVMAMA.order.ticket.addBxGoodIds(bxGoodsIds);
                      //var travNumType = $("#travNumType").val();
                      //var urlRequiredItem = "/scenic_front/book/ticket/requiredItem.do";
                      //if(travNumType=="TRAV_NUM_ALL"){
                      var  urlRequiredItem = "/scenic_front/book/ticket/requiredItemRsg.do";
                      //}
                      $.ajax({
                          url: urlRequiredItem,
                          data:{
                              productIds: JSON.stringify(productIds),
                              suppGoodsIds: JSON.stringify(goodsIds),
                              bxGoodsIds:JSON.stringify(bxGoodsIds),
                              bxCount: bxNumber
                          },
                          type:"post",
                          async : false,
                          success:function(data){
                            $("#userinfoDiv").html(data);
                            if($("#productTypeTxt").val()=="FOREIGNLINE" && (($("#categoryIdTxt").val() ==11 
                            		||$("#categoryIdTxt").val() ==12
                            		||$("#categoryIdTxt").val() ==13))){
                            	$("#userinfoDiv").find('input[type_name="chinese"]').each(function(){
                            		$(this).attr('type_name','chineseOrPinyin');
                            	});
                            }
                              if($('#userinfoDiv .msgCodeDiv').length>0&&!_lvPageTool.isLogin()){//未登录
                                  LVMAMA.order.ticket.bindMsgValid();
                              }else{//登录
                                  $('#userinfoDiv .msgCodeDiv').remove();
                              }
                            FRONT.book.user.travellersBindEvent();
                            LVMAMA.order.ticket.bxNumBussiness();
                            LVMAMA.order.ticket.initBxCheck();
                            LVMAMA.order.ticket.fillUserInfos();
                            $(".js_birthday").each(function () {
                                $(this).ui("calendar", {
                                    input: this,
                                    parm: {dateFmt: 'yyyy-MM-dd'}
                                })
                            });
                           },
                          complete:function(){
                              enableSubmitButton();
                          }
                    });
                },
                calTicketPersonCount: function () { //选择的门票计算人数
                    var adultCount = 0;
                    var childCount = 0;
                    var sum=0;
                    $(".js_input").each(function (i) {
                        var num = $(this).val();
                        var adult = $(this).attr("adult");
                        var child = $(this).attr("child");
                        if (LVMAMA.order.ticket.isTrueNumber(num)) {
                            num = parseInt(num);
                            if (adult != undefined && adult > 0) {
                                adultCount += parseInt(adult) * num;
                            }
                            if (child != undefined && child > 0) {

                                childCount += parseInt(child) * num;
                            }

                        }
                    });
                    sum = adultCount + childCount;
                    return sum;
                },
                calBaseTicketPersonCount: function () {
                    var mainInput = $(".ticketLi:visible input[mainitem=true]");
                    return parseInt(mainInput.attr("adult")) + parseInt(mainInput.attr("child"));
                },
                calbaoxianPersonCount: function () { //选择的保险计算人数
                	var bxCountnum=0; 
                	$("ul.js_bxtab li.active").each(function (i) {
                		var num=0;
                    	var goodsId=$(this).attr("data-id");
                        var productType=$(this).attr('productType');
                        if(goodsId!=undefined){
                             if(productType=="INSURANCE_739"){
                        	   num=1;
                             }else{
                              num =LVMAMA.order.ticket.calTicketPersonCount();
                             }
                             bxCountnum+=num;
                          }
                        }); 
                    return bxCountnum;
                },
                calcPriceInfo: function () {
                    $('dd.orderNumBox a.orderAdd').attr("disabled", 'disabled');
                    $('dd.orderNumBox a.orderReduce').attr("disabled", 'disabled');
                    cleanPromotion();
                    $.ajax({
                        type: "post",
                        url: "/scenic_front/book/ajax/priceInfo.do",
                        data: getFormData(),
                        dataType: "json",
                        success: function (data) {
                            ticketPriceinfoData = data;
                            firstCalAmt = true;
                            showBuyPresentActivityInfo(data);
                            showAmountInfo(data);
                        },
                        complete: function () {
                            $('dd.orderNumBox a.orderAdd').attr("disabled", false);
                            $('dd.orderNumBox a.orderReduce').attr("disabled", false);
                        }

                    });
                },
                //计算迪士尼演出票总数
                checkTotalNumDisneyTicket: function (num, goodsid) {
                    var msg = "";
                    var disneyTicketNum = 0;
                    $(".ticketLi:visible .js_input").each(function () {
                        if (!isNaN($(this).val()) && !isNaN($(this).attr("ticketDisneyNum"))) {
                            var ticketType = $(this).attr("ticketType");
                            var ticketDisneyNum = $(this).attr("ticketDisneyNum");//每一份迪士尼门票数（主要用于打包，单门票和其他票都是一）
                            var ticketName = $(this).attr("suppGoodsName");//如果是套票的话，在这里显示的是产品名称
                            var count = parseInt($(this).val());
                            if (goodsid == $(this).attr("goodsid")) {
                                count = parseInt(num);
                            }
                            if (ticketType == "DISNEY_TICKET") {
                                disneyTicketNum = disneyTicketNum + parseInt(count) * parseInt(ticketDisneyNum);
                                if (parseInt(count) > 0) {
                                    msg = msg + ticketName + "\n";
                                }
                            }
                        }
                    });
                    if (disneyTicketNum > 5) {
                        msg = msg + "的总票数不能超过5张";
                    } else {
                        msg = "";
                    }

                    return msg;
                },
                countDisneyTicketNum: function (num, goodsid) {
                    var disneyTicketNum = 0;
                    var disneyCurrentNum = 0;
                    var disneyCurrentOneNum = 1;
                    $(".ticketLi:visible .js_input").each(function () {
                        if (!isNaN($(this).val()) && !isNaN($(this).attr("ticketDisneyNum"))) {
                            var ticketType = $(this).attr("ticketType");
                            var ticketDisneyNum = $(this).attr("ticketDisneyNum");//每一份迪士尼门票数（主要用于打包，单门票和其他票都是一）

                            if (ticketType == "DISNEY_TICKET") {
                                if (goodsid == $(this).attr("goodsid")) {
                                    disneyCurrentNum = parseInt(num) * parseInt(ticketDisneyNum);
                                    disneyCurrentOneNum = ticketDisneyNum;
                                } else {
                                    var count = parseInt($(this).val());
                                    disneyTicketNum += parseInt(count) * parseInt(ticketDisneyNum);
                                }
                            }
                        }
                    });
                    if (disneyTicketNum + disneyCurrentNum > 5) {
                        return parseInt((5 - disneyTicketNum) / disneyCurrentOneNum);
                    } else {
                        return -1;
                    }
                },
                sortNumber: function (a, b) {
                    return a - b
                },
                couponSelect: function () {
                    /*$("#couponInputRadio").removeAttr("checked");*/
                },
                insuranceNumChange: function (o, operator) {
                    var num = 0;
                    var input = null;
                    if (operator == "") {
                        input = $(o);
                    } else {
                        input = $(o).siblings("input[type=text]");
                    }
                    num = input.val();
                    if (LVMAMA.order.ticket.notNumber(num)) {
                        num = 0;
                    }
                    num = parseInt(num);
                    var ticketNumber = parseInt(LVMAMA.order.ticket.calTicketPersonCount());//门票人数

                    if (operator == "+" && num < ticketNumber) {
                        num += LVMAMA.order.ticket.calBaseTicketPersonCount();
                    } else if (operator == "-" && num > LVMAMA.order.ticket.calBaseTicketPersonCount()) {
                        num -= LVMAMA.order.ticket.calBaseTicketPersonCount();
                    }

                    if (num < 0) {
                        num = 0;
                    }

                    if (num > ticketNumber) {
                        num = ticketNumber;
                    }

                    input.val(num);

                    //if(num>=ticketNumber){
                    //	LVMAMA.order.ticket.showInfo($(o),"最多预订数量3："+ticketNumber);
                    //}
                    /*if(num<=0){
                     LVMAMA.order.ticket.showInfo($(o),"至少预订数量："+0);
                     }*/

                    this.bxNumBussiness();
                    bookNumOnchangeCallback.invoke();
                },
                showInfo: function (o, msg) {
                    var obj = o.parent(); //提示出现的模块位置
                    var text = msg; //提示的文字
                    var left = -5; //提示的left微调
                    var top = 15; //提示的top微调
                    //nameFull(obj,text,left,top); //提示调用的方法
                    var type = 'warning'; //warning(感叹号)；
                    nameFull(obj, text, left, top, type);//提示调用的方法
                },
                bxNumBussiness: function () {
                    this.bxChangeAction();
                },
                hideNeedVisitDate: function () {
                    $('.js_youwanTime').removeClass('js_yz');
                    removeTips();
                },
                bxChangeAction: function () {
                    //isTicketNumChange 是否由于门票数量变化导致
                    //var ticketNumber = parseInt(LVMAMA.order.ticket.calTicketPersonCount());//门票人数
                	$("#insuranceSubmit").html("");
                    $("ul.js_bxtab li").each(function (i) {
                        var isChoice = $(this).hasClass('active');
                       /* $isbacktochangebxflag=$(this).attr('isbacktochangebxflag');*/
                        var productType=$(this).attr('productType');
                        var bxGoodsId=$(this).attr("data-id");
                        var bxNum = 0;
                        if (isChoice&&bxGoodsId!=undefined) {
                           /* if (i == 0&&typeof($isbacktochangebxflag)=="undefined") {
                                $('.toubao_text').hide();
                                return; //不购买保险
                            }*/
                            $('.toubao_text').show();                         
                            bxNum=LVMAMA.order.ticket.getInsuranceNum(bxGoodsId);
                            LVMAMA.order.ticket.setInsuranceNum(bxNum);
                            var goodsId = $(this).attr('data-id');
                            LVMAMA.order.ticket.setHideBxGoodsInput(goodsId, bxNum,productType);
                            LVMAMA.order.ticket.setBxCheckBoxName(goodsId);//待看
                            //LVMAMA.order.ticket.dealInsurancePersonBox();
                        }
                    });
                },
                setHideBxGoodsInput: function (goodsId, bxNum,productType) {
                	var insuranceSubmitHtml='<input type="hidden" id="bxGoodsId" name="itemMap[' + goodsId + '].goodsId" value="'+goodsId+'" autocomplete="off"/>'
                	+'<input type="hidden" id="bxGoodsBookQuantity" name="itemMap[' + goodsId + '].quantity" value="'+bxNum+'" autocomplete="off"/>'
                	+'<input type="hidden" id="bxGoodsBookProductType" name="itemMap[' + goodsId + '].productType" value="'+productType+'" autocomplete="off"/>';
                    $("#insuranceSubmit").append(insuranceSubmitHtml);
                },
                dealInsurancePersonBox: function () {
                    this.checkInsurancePersonBox();
                    this.baoxianPersonsShowHide();
                },
                checkInsurancePersonBox: function () {
                    var bxNum = this.calbaoxianPersonCount();
                    $("dl.user_dl.bx_check dd input").each(function (i) {
                        if (i < bxNum) {
                            $(this).attr("checked", "checked");
                        }
                    });
                },
                setBxCheckBoxName: function (goodsId) {
                    $("dl.js_user_dl.bx_check").each(function (k) {
                        $(this).find("input[type=hidden]").attr("name", "personRelationMap[GOODS_" + goodsId + "].itemPersonRelationList[" + k + "].seq");
                    });
                },
                //检查是否选择保险
                checkSelectedInsurance: function () {
                	var bxGoodsIdList=[];
                	$("ul.js_bxtab li.active").each(function(){
                		var bxGoodsId=$(this).attr("data-id");
                		if(bxGoodsId != undefined){
                		 bxGoodsIdList.push(bxGoodsId);
                		}
                	});
                   return bxGoodsIdList.length>0;
                },
                setInsuranceNum: function (num) {
                    //设置购买保险的个数
                    $("#insuranceNumInput").val(num);
                },
                getInsuranceNum: function (bxGoodsId) {
                    //如果有选择保险那么保险数应该等于门票分数，否则为0
                    //update by luo
                    var bxNum = 0;
                    if (bxGoodsId!=undefined && LVMAMA.order.ticket.checkSelectedInsurance()) {
                    	var num=0;
                    	$("ul.js_bxtab li.active").each(function (i) {
                    	var goodsId=$(this).attr("data-id");
                        var productType=$(this).attr('productType');
                        if(goodsId==bxGoodsId){
                             if(productType=="INSURANCE_739"){
                        	   num=1;
                             }
                             if(num==0){
                             bxNum = LVMAMA.order.ticket.calTicketPersonCount();
                             }else{
                             bxNum=num;
                             } 
                           return;
                          }
                        }); 
                     }       
                    return bxNum;
                },
                initBxCheck: function () {

                    LVMAMA.order.ticket.baoxianPersonsShowHide(); //update by luo


                    //初始化优惠券
                    $('input[type=radio][name=youhui]:checked').each(function () {
                        var v = $(this).val();
                        if (v == "false") {
                            //$(this).closest("dd").find("div.pro_info.yh_info").css('display','none');
                            $("#coupon_info").css('display', 'none');
                            $("#bonus_info").css('display', 'none');
                        }
                        if (v == "coupon") {
                            //$(this).closest("dd").find("div.pro_info.yh_info").css('display','block');
                            $("#coupon_info").css('display', 'block');
                            $("#bonus_info").css('display', 'none');
                        }
                        if (v == "bonus") {
                            $("#coupon_info").css('display', 'none');
                            $("#bonus_info").css('display', 'block');
                        }

                    });

                    //初始化其他票 update by luo
                    /*$("li.table_4 span input").each(function(i){
                     var num=$(this).val();
                     var mainItem=$(this).attr("mainItem");
                     if(LVMAMA.order.ticket.isTrueNumber(num)&&mainItem=="false"){
                     $(this).closest("dd").find("div.table_list.table_t").css('display','block');
                     $(this).closest("dd").find("a.btn_qita").css('display','none');
                     $(this).closest("dd").find("a.btn_qita").addClass('jt_up');
                     }
                     });*/

                },//刷新保险
                refereshInsurance: function () {
                    var payTarget = $("#payTarget").val();
                    var aperiodicFlag = $("#aperiodicFlag").val();
                    var packageType = $("#packageType").val();
                    if (payTarget != "PREPAID" || aperiodicFlag == "Y"||packageType=="LVMAMA") {
                        return;
                    }
                    var productId = $("#productIdTxt").val();
                    var suppGoodsIdList="";
                    var goodsAtAnyTimeAndOverdueDeductFlag=$("#goodsAtAnyTimeAndOverdueDeductFlag").val();
                    var visitTime = getVisitTime();
                    var suppPrice = LVMAMA.order.ticket.fillSuppGoodsOrderInfo();
                    $(".ticketLi:visible .js_input").each(function () {
                    	suppGoodsIdList+=$(this).attr("goodsId")+",";
                    });
                    disableSubmitButton();
                    $.ajax({
                        type: "post",
                        async: false,
                        url: "/scenic_front/book/ticket/refereshInsurance.do",
                        data: {productId: productId,suppGoodsIds:suppGoodsIdList, visitTime:visitTime, 
                        	  suppPrice:suppPrice,goodsAtAnyTimeAndOverdueDeductFlag:goodsAtAnyTimeAndOverdueDeductFlag},
                        dataType: "html",
                        success: function (data) {
                            $("#insuranceDiv").html(data);
                            LVMAMA.order.ticket.initBxCheck();
                            //LVMAMA.order.ticket.bindInsuranceEvent(); //update by luo
                            LVMAMA.order.ticket.bxChangeAction();
                        },
                        complete:function(){
                            enableSubmitButton();
                        }
                    });
                },
                bindInsuranceEvent: function () {
                    // 增加保险人数
                    $('#insuranceAdd').click(function () {
                        LVMAMA.order.ticket.insuranceNumChange(this, "+");
                    });

                    // 减少保险人数
                    $('#insuranceSub').click(function () {
                        LVMAMA.order.ticket.insuranceNumChange(this, "-");
                    });
                },

                refereshOtherTicket: function () {
                    var payTarget = $("#payTarget").val();
                    var limitChild= $("input[name='limitChild']").val();
                    var aperiodicFlag = $("#aperiodicFlag").val();
                    if (payTarget != "PREPAID" || aperiodicFlag == "Y") {
                        return;
                    }
                    var suppGoodsId = "";
                    $(".ticketLi:visible .js_input").each(function () {
                        var goodsId = $(this).attr("goodsId");
                        var mainItem = $(this).attr("mainItem");
                        if (mainItem == "true") {
                            suppGoodsId = goodsId;
                            return;
                        }
                    });
                    var visitTime = getVisitTime();
                    if (suppGoodsId == "" || $('.js_add_ticket').length == 0) {
                        return;
                    }
                    disableSubmitButton();
                    //刷新弹出层
                    $.ajax({
                        type: "post",
                        async: false,
                        url: "/scenic_front/book/ticket/refereshOtherTicket.do",
                        data: {suppGoodsId: suppGoodsId, visitTime: visitTime, returnPage: "new_other_goods_info",limitChild:limitChild},
                        dataType: "html",
                        success: function (data) {
                            $("#otherTicketDiv").html(data);
                            //$('.btn_qita').show().removeClass('jt_up');
                            //$('#otherTicketDiv').find('.table_t').hide();
                            LVMAMA.order.ticket.bindOtherTicketEvent();
                        },
                        complete:function(){
                            enableSubmitButton();
                        }
                    });

                    disableSubmitButton();
                    //刷新主页面中的其他商品
                    $.ajax({
                        type: "post",
                        async: false,
                        url: "/scenic_front/book/ticket/refereshOtherTicket.do",
                        data: {suppGoodsId: suppGoodsId, visitTime: visitTime, returnPage: "new_other_goods_info_main",limitChild:limitChild},
                        dataType: "html",
                        success: function (data) {
                            $("#mainOtherTicketDiv").html(data);
                        },
                        complete:function(){
                            enableSubmitButton();
                        }
                    });

                    select_goodsIds.length = 0;
                    temp_select_goodsIds.length = 0;

                    selectSuppGoodsLastStyle();
                },
                refereshTicketList: function () {
                    var payTarget = $("#payTarget").val();
                    var limitChild= $("input[name='limitChild']").val();
                    var aperiodicFlag = $("#aperiodicFlag").val();
                    if (payTarget != "PREPAID" || aperiodicFlag == "Y") {
                        return;
                    }
                    var suppGoodsIds = "";
					var bookNums = "";
                    $(".ticketLi:visible .js_input").each(function () {
                        var goodsId = $(this).attr("goodsId");
						suppGoodsIds=suppGoodsIds+goodsId+"_";
						
						var bookNum = $(this).val();
						bookNums=bookNums+bookNum+"_";
                    });
                    suppGoodsIds=suppGoodsIds.substring(0,suppGoodsIds.length-1);
					bookNums=bookNums.substring(0,bookNums.length-1);
                    var visitTime = getVisitTime();
                    if (suppGoodsIds == "") {
                        return;
                    }
                    disableSubmitButton();
                    //刷新商品列表
                    $.ajax({
                        type: "post",
                        async: false,
                        url: "/scenic_front/book/ticket/refereshTicketList.do",
                        data: {suppGoodsIds:suppGoodsIds,bookNums:bookNums,visitTime: visitTime,limitChild:limitChild},
                        dataType: "html",
                        success: function (data) {
                            $("#park_days_goods_list_div").html(data);
                            LVMAMA.order.ticket.bindOtherTicketEvent();
                        },
                        complete:function(){
                            enableSubmitButton();
                        }
                    });
                    select_goodsIds.length = 0;
                    temp_select_goodsIds.length = 0;

                    selectSuppGoodsLastStyle();
                },
                bindOtherTicketEvent: function () {
                    // 增加门票人数
                    $('#otherTicketDiv a.orderAdd').bind('click', function () {
                        LVMAMA.order.ticket.bookNumOnchangeComm(this, "+");
                    });

                    // 减少门票人数
                    $('#otherTicketDiv a.orderReduce').bind('click', function () {
                        LVMAMA.order.ticket.bookNumOnchangeComm(this, "-");
                    });
                },
                showErrorInfo: function (showFlag, msg) {
                    if (showFlag) {
                        //$("#ticketErrorInfoDiv").find("div").html("<span class='tip-icon tip-icon-big-warning'></span>" + msg);
                        //$("#ticketErrorInfoDiv").show();
                        topTip(msg);
                    } else {
                        $('.top_tip_box').remove();
                    }

                },
                getDoSubmitFlag: function () {
                    return doSubmitFlag
                },
                baoxianPersonNumCheck: function (obj) {
                    var bxCount = 0;
                    var bxNumber = LVMAMA.order.ticket.calbaoxianPersonCount();
                    $("dl.user_dl.bx_check dd label input[type=checkbox]:checked").each(function (i) {
                        bxCount = parseInt(bxCount) + parseInt(1);
                    });
                    if (bxCount > bxNumber) {
                        LVMAMA.order.ticket.showInfo($(obj), "被保险人最多：" + bxNumber + "人");
                        $(obj).removeAttr("checked");
                    }
                },
                baoxianPersonsShowHide: function () {
                    var bxNumber = LVMAMA.order.ticket.calbaoxianPersonCount();
                    var ticketNumber = LVMAMA.order.ticket.calTicketPersonCount();//门票人数
                    var bxCheckBoxes = $("dl.js_user_dl.bx_check dd input");
                    var $bxCheckBox = null;
                    if (ticketNumber == bxNumber || bxNumber == 0) {
                        bxCheckBoxes.each(function () {
                            $bxCheckBox = $(this).parents('.bx_check.js_user_dl');
                            $bxCheckBox.hide();
                            $bxCheckBox.find("input[type=hidden]").attr("name","");
                        });
                    } else {
                        bxCheckBoxes.each(function (i) {
                            $bxCheckBox = $(this).parents('.bx_check.js_user_dl');
                            $bxCheckBox.show();
                            if(i!=0){
                                $bxCheckBox.find("input[type=hidden]").attr("name","");
                            }
                        });
                    }
                },
                //点评的返现金额单位是元
                getTicketGoodsRebateAmount: function () {
                    disableSubmitButton();
                    $.ajax({
                        type: "post",
                        async: false,
                        url: "/scenic_front/book/ajax/getGoodsRebateAmount.do",
                        data: getFormData(),
                        dataType: "json",
                        success: function (data) {
                            if (data.success) {
                                var goodsRebateAmountMap = data.attributes.goodsRebateAmountMap;
                                $(".ticketLi:visible .js_input").each(function (i) {
                                    var goodsId = $(this).attr("goodsId");
                                    var productId = $(this).attr("productId");
                                    var js_input = $(this);
                                    $.each(goodsRebateAmountMap, function (k, v) {
                                        if (k == goodsId || k == productId) {
                                            $.each(v, function (i, obj) {
                                                if (obj != undefined && obj > 0) {
                                                    //新的下单页只处理pc返现
                                                    if (i == "pcRebate") {
                                                        /*rebateStr+="<span tip-content='预订此产品，游玩后发表体验点评，内容通过审核，即可获得最高&lt;span&gt;"+obj+"&lt;/span&gt;元点评奖金返现。' tip-title='写体验点评返奖金' class='tagsback tagsback-orange'><em>返</em><i>￥"+obj+"元</i></span>";*/
                                                        js_input.attr("pc_rebate", obj);
                                                    } else if (i == "mobileRebate") {
                                                        js_input.attr("mobile_rebate", obj);
                                                        /*rebateStr+="<span tip-content='通过驴妈妈旅游客户端预订，发表点评即可多返"+obj+"元奖金。' class='tagsback tagsback-app'>+"+obj+"元</span>";*/
                                                    }
                                                }
                                            });
                                            return;
                                        }
                                    });
                                });
                            }
                        },
                        complete:function(){
                            enableSubmitButton();
                        }
                    });
                },
                //绑定短信验证
                bindMsgValid: function () {
                    var _zUserInfo = {
                        times: 60,
                        autoTask : null,
                        downTime : true,
                        clickDown:false
                    };
                    //单个blur校验
                    $('.msgCode').die().live('blur',function(){
                        var _codeReg  =/^\d{6}\b/;//判断是否为6位数字
                        var _this = $(this);
                        var value = $.trim(_this.val());
                        if( value==''){
                            _this.addClass('yz_error').siblings('.error_text').css('display','inline-block').html('<i class="tip-icon tip-icon-error"></i>请输入验证码。').siblings('.ts_text').hide();
                        }else if(_codeReg.test(value)){
                            _this.removeClass('yz_error').siblings('.error_text').css('display','none').siblings('.ts_text').show();
                        }else if(!_codeReg.test(value)){
                            _this.addClass('yz_error').siblings('.error_text').css('display','inline-block').html('<i class="tip-icon tip-icon-error"></i>请输入6位数字验证码。').siblings('.ts_text').hide();
                        }else{
                            _this.removeClass('yz_error').siblings('.error_text').css('display','none').siblings('.ts_text').show();
                        }
                    });
                    var sendSMSTask=function () {
                        if(_zUserInfo.times==60 && _zUserInfo.downTime){
                            _zUserInfo.downTime = false;
                            var jThis = $("#sendValidSms");
                            jThis.html('<em class="c_f60">60</em>秒后重发').addClass('disabled');
                            _zUserInfo.autoTask = setInterval(function(){
                                _zUserInfo.times--;
                                jThis.find('em').html(_zUserInfo.times);
                                if(_zUserInfo.times==0){
                                    clearInterval(_zUserInfo.autoTask);
                                    jThis.html('重发验证码').removeClass('disabled');
                                    _zUserInfo.times=60;
                                    _zUserInfo.downTime = true;
                                    _zUserInfo.clickDown=false;
                                }
                            },1000);
                        }
                    };
                    //发送短信验证码
                    $("#sendValidSms").die().live('click',function(){
                        if(_zUserInfo.clickDown){
                           return;
                        }else {
                            if (_zUserInfo.times != 60 || !_zUserInfo.downTime) {
                                return;
                            }
                            var jMobile = $("#" + $("#msgCode").attr("tel-id"));
                            if (_lvPageTool.isLogin()) {
                                return;
                            }
                            var validCheck = true;
                            if (!jMobile || $.trim(jMobile.val()).length <= 0 || !_lvPageTool.isMobile(jMobile.val())) {
                                jMobile.addClass('yz_error').siblings('.error_text').hide().siblings('.ts_text').hide();
                                jMobile.siblings('.error_text[zItem="exception"]').css('display','inline-block').siblings('.ts_text').hide();
                                validCheck = false;
                            }
                            if (!validCheck) {
                                return;
                            }
                            _zUserInfo.clickDown = true;
                            //发送短信验证码
                            //http://login.lvmama.com/nsso/ajax/message/mobileLogByPC/sendMobileCode.do
                            //getjson没有错误处理方法，使用ajax
                            //景点门票，其它票，组合票
                            var ajax_url ='http://login.lvmama.com/nsso/ajax/sendTicketAuthenticationCode.do?jsoncallback=?';
                            $.ajax({  type: "get",contentType: "application/json; charset=utf-8",dataType: "JSONP",url: ajax_url,timeout: 5000,
                                data :{mobileOrEMail: jMobile.val(), verifycode: ''},
                                success: function (data) {
                                    if (data.success) {
                                        $('#msgCode').removeClass('yz_error').siblings('.error_text').css('display','none').siblings('.ts_text').show();                                        sendSMSTask();//发送成功，开始倒计时
                                    } else {
                                        _zUserInfo.clickDown = false;
                                        var errorTips = '';
                                        if (data.errorText == 'errorVerifycode') {
                                            errorTips = '验证码发送失败';
                                            msgValid($('#msgCode'), errorTips);
                                        } else if (data.errorText == 'vcodeWarning') {
                                            errorTips = '你当前短信验证码已失效，请重新发送验证码';
                                            msgValid($('#msgCode'), errorTips);
                                        } else if (data.errorText == 'phoneWarning') {
                                            errorTips = '已超过每日发送上限，请次日再试';
                                            msgValid($('#msgCode'), errorTips);
                                        } else if (data.errorText == 'ipLimit') {
                                            errorTips = '当前IP发送过快，请稍后再试';
                                            msgValid($('#msgCode'), errorTips);
                                        } else if (data.errorText == 'waiting') {
                                            errorTips = '发送频率过快，请稍后再试';
                                            msgValid($('#msgCode'), errorTips);
                                        } else {
                                            errorTips = data.errorText;
                                            msgValid($('#msgCode'), "验证码发送失败");
                                        }
                                    }
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    _zUserInfo.clickDown = false;
                                    msgValid($('#msgCode'), "请求超时:验证码发送失败");
                                }
                            });
                        }
                        var msgValid=function (obj,text) {
                            obj.addClass('yz_error').siblings('.error_text').css('display','inline-block').html('<i class="tip-icon tip-icon-error"></i>'+ text +'。').siblings('.ts_text').hide();
                        };

                    });
                },
                ajaxValidCode: function (obj,callback) {//ajax验证短信验证码，景乐产品下单
                    var jMobile = $("#"+$("#msgCode").attr("tel-id"));
                    //先验证验证码是否满足6个数字
                    var _codeReg  =/^\d{6}\b/;//判断是否为6位数字
                    var value = $.trim(obj.val());
                    if( value==''){
                        obj.addClass('yz_error').siblings('.error_text').css('display','inline-block').html('<i class="tip-icon tip-icon-error"></i>请输入验证码。').siblings('.ts_text').hide();
                        obj.focus();
                        return;
                    }else if(_codeReg.test(value)){
                        obj.removeClass('yz_error').siblings('.error_text').css('display','none').siblings('.ts_text').show();
                    }else if(!_codeReg.test(value)){
                        obj.addClass('yz_error').siblings('.error_text').css('display','inline-block').html('<i class="tip-icon tip-icon-error"></i>请输入6位数字验证码。').siblings('.ts_text').hide();
                        obj.focus();
                        return;
                    }else{
                        obj.removeClass('yz_error').siblings('.error_text').css('display','none').siblings('.ts_text').show();
                        obj.focus();
                        return;
                    }
                    $.ajax({
                        url: 'http://login.lvmama.com/nsso/ajax/validateTicketAuthenticationCode.do?jsoncallback=?',
                        type: 'GET',
                        dataType: 'JSONP',
                        data:{mobile: jMobile.val(), authenticationCode: value},
                        timeout: 5000,
                        success: function (data) {
                            if(data.success){
                                callback();
                            }else {
                                if(data.errorNum&&data.errorNum>5){//短信验证码次数失败次数超过五次，显示图形验证码
                                    //msgValid('','短信验证码次数失败次数超过五次，显示图形验证码');
                                    obj.addClass('yz_error').siblings('.error_text').css('display','inline-block').html('<i class="tip-icon tip-icon-error"></i>无效的验证码。').siblings('.ts_text').hide();
                                    obj.parents('dl').next().append('<input type="hidden" name="checkCodeValid" id="checkCodeValid" value="0"/>').show();
                                    obj.focus();
                                }else {//其他错误
                                    obj.addClass('yz_error').siblings('.error_text').css('display','inline-block').html('<i class="tip-icon tip-icon-error"></i>无效的验证码。').siblings('.ts_text').hide();
                                    obj.focus();
                                }
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            console.log('请求超时');
                            obj.addClass('yz_error').siblings('.error_text').css('display','inline-block').html('<i class="tip-icon tip-icon-error"></i>短信验证码验证失败。').siblings('.ts_text').hide();
                            obj.focus();
                        }
                    });
                }
            }
        }
 };
function contactsPersonCheckboxFalse(){
		$("input[name='contactsPersonCheckbox']").attr("checked",false);
}

function checkCircusStock(){
    $('.js_select_circus').removeClass('input_red');
    $('#circus .d_floatTip').hide();

    //库存弹层loading
    var $loginDom = "<div class=\"d_bigerload d_alertBox\">正在努力检查库存中，请耐心等候...</div>";
    showDialog($loginDom);
    setTimeout(function() {
        var circusCount = LVMAMA.order.ticket.getCircusStock();
        $('.dialog-close').trigger('click'); //关闭loading的盒子
    },100);

}

function showDialog(context){
    pandora.dialog({
        title: "",
        content: context
    });
}

var _lvPageTool = {
	isMobile: function( mobileVal ){
		var _mobile = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17\d{1})|(18([0-4]|[5-9])))\d{8}$/;
		if(mobileVal!='' && _mobile.test(mobileVal)){
			return true;
		}
		return false;
	},
	isLogin: function(){
		var isLogin =  $("#login_user").attr("status");
		return isLogin==1;
	},
	refreshDeliverMobileComment: function(zItemFocus){
		$.each( $("[item_type='main_deliv']").siblings("span"), function(i, n){
			var jItem = $(n);
			if(jItem.attr("zItem")==zItemFocus){
				jItem.css("display", "inline-block");
			}
			else{
				jItem.css("display", "none");
			}
		});
	},
	isFrozenMobile: function(pSetting){
		$.ajax({
			type:"GET",
			async: false,
			dataType: "JSONP",
			url: "http://login.lvmama.com/nsso/ajax/checkAccountStatus.do?jsoncallback=?",
			data: {mobile: pSetting.mobileVal},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
					$("#isFrozenFlag").attr("value",'N');
				   },
			success: function(response){
				if(response.success==false){	//condition: 是冻结手机号
					$("#isFrozenFlag").attr("value",'Y');
					pSetting.frozenFun.call(this);
				}else{
					$("#isFrozenFlag").attr("value",'N');
					pSetting.isLvmmFun.call(this);
				}
			}
		});
	}
};
String.prototype.format = function(){    
    var args = arguments;    
    return this.replace(/\{(\d+)\}/g,                    
        function(m,i){    
            return args[i];    
        });    
};

Array.prototype.indexOf = function(val) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == val) return i;
	}
	return -1;
};


Array.prototype.baohanstr = function(val) {
	for (var i = 0; i < this.length; i++) {
		if (this[i].indexOf(val) != -1) return this[i];
	}
	return -1;
};

Array.prototype.remove = function(val) {
	var index = this.indexOf(val);
		if (index > -1) {
	this.splice(index, 1);
	}
};

function getYouHuiCN(str){
		switch(str){
		    case 'BounsPayLi':		    	
		    	return '奖金抵扣';
			case 'CashsPayLi':
				return '账户存款抵扣';
			case 'showCZK':
				return '储值卡';
			case 'showLPK':
				return '礼品卡';
			case 'BounsPayLi_hk':
				return '游乐保权益';
			default:	 
			return '优惠券';
		}
};
function insurance(str){
	
	 $.ajax({
         type: "post",
         async: false,
         url: "/scenic_front/book/ticket/getInsurance2.do",
         data: {suppGoodsIds: str},
         dataType: "html",
         success: function (data) {
           var result = JSON.parse(data);
           var insuranceInfo = JSON.parse(JSON.stringify(result.attributes))
           document.getElementById("goods_id").innerHTML = insuranceInfo.goodsId;
           document.getElementById("goods_name").innerHTML = insuranceInfo.goodsName;
           document.getElementById("insurance_price").innerHTML = "￥" + insuranceInfo.price;
           document.getElementById("policy_type").innerHTML = insuranceInfo.policyType;
           document.getElementById("under_writing_agency").innerHTML = "承保机构：" + insuranceInfo.underwritingAgency;
           document.getElementById("sales_agent").innerHTML = "销售代理：" + insuranceInfo.salesAgent + " (<a style='color:blue' onclick=\"window.open('/scenic_front/insurance/notification.html')\">查看客户告知书</a>)";
           var description_part1 = "投保前请先阅读 <a style=\"color:blue\" onclick=\"window.open('/scenic_front/insurance/instruction4";
           var description_part2 = ".html')\">投保须知</a>、<a style=\"color:blue\" onclick=\"window.open('/scenic_front/insurance/term4";
           var description_part3 = ".html')\">保险条款</a>、<a style=\"color:blue\" onclick=\"window.open('/scenic_front/insurance/exemption.html')\">免责声明</a>、<a style=\"color:blue\" onclick=\"window.open('/scenic_front/insurance/confirmation.html')\">被保险人同意说明</a>"
           var policy_type = "ticket"; 
           if (insuranceInfo.policyType.indexOf("门票") >= 0)
        	   policy_type = "ticket";
           else
        	   policy_type = "trip";
           document.getElementById("insurance_description").innerHTML = description_part1 + policy_type + description_part2 + policy_type + description_part3;
           document.getElementById("term").innerHTML = "您已进入<font style='color:#00BFFF;'>" + insuranceInfo.salesAgent + "</font>投保页面，为保障您的合法权益，请仔细阅读保险条款等内容。根据相关法规要求，您在保险销售页面的操作轨迹将会被记录。本产品由<font style='color:#00BFFF;'>" + insuranceInfo.salesAgent + "</font>销售";
         }
     });	
};

function showPopup() {
	var insurance_list = document.getElementById("ticket_insurance");
	if (insurance_list == undefined)
		return;
	
	var insurance_id = document.getElementById("goods_id").innerHTML;
	var insurance = document.getElementById("insurance_" + insurance_id);
	if (insurance.getAttribute("class").indexOf("active") < 0)
		return;
	
	var names = document.getElementsByClassName("input js_yz empty_check name");
	var recognizees = "";
	for (i = 0; i<names.length; i++) {
		if (names[i].value == "")
			return;
		
		recognizees += names[i].value;
		if (i < names.length -1)
			recognizees += "、";
	}
	document.getElementById("recognizees").innerHTML = "被保人        " + recognizees;
	document.getElementById('insurancePop').style.display='block';
	document.getElementById('insurance_warning').style.display='block';
}